Here is a code:
#Override
public Article insert(Article article,String sql) {
try {
pr = super.get(sql);
pr.setInt(1, article.getId());
pr.setString(2, article.getName());
pr.setString(3, article.getDescription());
pr.setString(4, article.getAuthor());
pr.setString(5, article.getPicture_url());
pr.setDouble(6, article.getPrice());
pr.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
DbHandler.showErrorMessage(e);
}
return article;
}
#XmlRootElement
public class Article {
private String name;
private String description;
private String picture_url;
private String author;
private int id;
private double price;
public Article() {
// TODO Auto-generated constructor stub
}
public Article(String name, String description, String picture_url, String author, int id, double price) {
super();
this.name = name;
this.description = description;
this.picture_url = picture_url;
this.author = author;
this.id = id;
this.price = price;
}
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getPicture_url() {
return picture_url;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Article insert(Article article) {
return repo.insert(article, "insert into book values (?, ? , ? , ? , ? , ?)");
}
When i try to insert the Article in database with POST method every time i have MySQLIntegrityConstraintViolationException and the message is 'name can not be null'? Can someone help me what is the problem here?
And also i have database table with two primary keys with id and name
This is a screenshot in postman
enter image description here
Related
I am trying to , create a list view that allows a user to browse and borrow books, so as a data source I want to load and mapp the XML into objects handled in memory. in spring boot, I am very new to java and spring boot, I got this error:
**javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"catalog"). Expected elements are (none)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:712)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:232)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:227)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:94)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1117)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:542)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:524)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:137)
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3058)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:820)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:601)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:531)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:885)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:821)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:639)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:228)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:199)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:140)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:179)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:164)
at com.task1.task1.Task1Application.main(Task1Application.java:25)
**
Here is my Book.java class:
public class Book {
private String author;
private String price;
private String genre;
private String description;
private String id;
private String title;
private String publish_date;
public Book() {}
public Book(String author, String price, String genre, String description, String id, String title, String publish_date) {
super();
this.author = author;
this.price = price;
this.genre = genre;
this.description = description;
this.id = id;
this.title = title;
this.publish_date = publish_date;
}
public String getAuthor ()
{
return author;
}
public void setAuthor (String author)
{
this.author = author;
}
public String getPrice ()
{
return price;
}
public void setPrice (String price)
{
this.price = price;
}
public String getGenre ()
{
return genre;
}
public void setGenre (String genre)
{
this.genre = genre;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTitle ()
{
return title;
}
#XmlElement(name = "title")
public void setTitle (String title)
{
this.title = title;
}
public String getPublish_date ()
{
return publish_date;
}
public void setPublish_date (String publish_date)
{
this.publish_date = publish_date;
}}
And here is my Catalog.java class:
public class Catalog {
private List<Book> books;
public Catalog() {}
public Catalog(List<Book> books) {
super();
this.books = books;
}
#XmlElement
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}}
And here is my main file:
public static void main(String[] args) throws JAXBException, IOException {
try {
File file = new File("books.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Catalog.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Catalog que= (Catalog) jaxbUnmarshaller.unmarshal(file);
System.out.println("Books:");
List<Book> list=que.getBooks();
for(Book bk:list)
System.out.println(bk.getId()+" "+bk.getAuthor()+" "+bk.getTitle());
} catch (JAXBException e) {
e.printStackTrace();
}
}}
My books.xml file is here:
https://pastebin.com/C8udk7Mj
Please let me know how can I fix this and how can I proceed to use the local host and allow boreowing the books ...
I've checked and can confirm. You need to
add #XmlRootElement(name = "catalog") on your Catalog class to tell JAXB this can be at the root
change annotation to #XmlElement(name="book") on getBooks() method (otherwise doesn't match, look for books)
add annotation #XmlAttribute on Book setId method (otherwise you end up with empty ids)
And then your code works:
Books:
bk101 Gambardella, Matthew XML Developer's Guide
bk102 Ralls, Kim Midnight Rain
...
I am using SQLite to store my information. I am storing the date as string format. Now I want to fetch the data based on the date, there might be more than one data for a single date. I have checked relevant questions and tried in my way but can not find the solution. Though I was able to get info of a single data for a particular date.
My code for fetching data from the database:
public ArrayList<ExpenseModel> getSingleExpenseDetails(String date){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
String query = "select * from " + TABLE_SAVE_EXPENSE + " where "+ COLUMN_EXPENSE_DATE+ " = '" + date+ "'";
Cursor cursor=sqLiteDatabase.rawQuery(query, null);
ExpenseModel expenseModel=new ExpenseModel();
ArrayList<ExpenseModel> expenseModels = new ArrayList<>();
Log.v("Title : ",""+title);
if (cursor.moveToFirst()){
do {
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
return expenseModels;
}
ExpenseModel class:
package app.shakil.com.dailyexpense.Models;
public class ExpenseModel {
private int id;
private String title;
private String description;
private String date;
private int amount;
private String currency;
public ExpenseModel(){
}
public ExpenseModel(String title,String description,String date,int amount,String currency){
this.title=title;
this.description=description;
this.date=date;
this.amount=amount;
this.currency=currency;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
One obvious mistake that you do in your code is that you initialize expenseModel before the loop and use it inside the loop for all the rows:
ExpenseModel expenseModel=new ExpenseModel();
Move that line inside the loop:
do {
ExpenseModel expenseModel=new ExpenseModel();
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}
Hello guys I am developing an app where I am using Hibernate, jpa and mysql. I know that this my question is possible duplicate but that questions did not help me. I have two tables in database:book and author, where id_author is a foreign key in book. I want to make one-to-many relationship, but I have this error:
Caused by: org.hibernate.MappingException: Could not determine type for: com.entity.Author, at table: Book, for columns: [org.hibernate.mapping.Column(author)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398)
at org.hibernate.mapping.Property.isValid(Property.java:225)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 9 more
This is my Book class:
#XmlRootElement
#Entity
public class Book {
private Author author;
#Column(name = "name")
String name;
#Column(name = "isbn")
String isbn;
#Column(name = "price")
int price;
#Column (name = "publishedDate")
Date publishedDate;
#ManyToOne(cascade = CascadeType.ALL)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Book(Author author, int id, String name, String isbn, int price, Date publishedDate) {
super();
this.author = author;
this.id = id;
this.name = name;
this.isbn = isbn;
this.price = price;
this.publishedDate = publishedDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public Book(String name, String isbn, int price, Date publishedDate) {
super();
this.name = name;
this.isbn = isbn;
this.price = price;
this.publishedDate = publishedDate;
}
#Id
#GeneratedValue
#Column(name="book_id")
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book(Author author, int id, String name, String isbn, int price, Date publishedDate, int author_id) {
super();
this.author = author;
this.id = id;
this.name = name;
this.isbn = isbn;
this.price = price;
this.publishedDate = publishedDate;
this.author_id = author_id;
}
public int getAuthor_id() {
return author_id;
}
public void setAuthor_id(int author_id) {
this.author_id = author_id;
}
#Column(name="author_id")
int author_id;
public Book(){}
}
This is my author class:
#Entity
public class Author {
private int author_id;
private String author_name;
private String author_surname;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getAuthor_id() {
return author_id;
}
public void setAuthor_id(int author_id) {
this.author_id = author_id;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getAuthor_surname() {
return author_surname;
}
public void setAuthor_surname(String author_surname) {
this.author_surname = author_surname;
}
public Author(int author_id, String author_name, String author_surname) {
super();
this.author_id = author_id;
this.author_name = author_name;
this.author_surname = author_surname;
}
}
Could someone tells me where am I mistaking?
Thanks in advance.
Trying to figure out how to use hibernate to call to get a list of the movies for a given genre?!
I tried getting a given genre then using the method from GenreDTO to get the set of movies.
Query hqlQuery = session.createQuery("FROM GenreDTO WHERE genre like :genre");
GenreDTO g = hqlQuery.setParameter("title","%" + term + "%").uniqueResult();
return g.getMovies();
Is there a better way?
CREATE TABLE Movie (
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
title VARCHAR(255),
poster VARCHAR(255),
director VARCHAR(255),
actors VARCHAR(255),
synopsis VARCHAR(3000),
release_date TIMESTAMP
);
CREATE TABLE Genre(
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
genre VARCHAR(255)
);
CREATE TABLE MovieHasGenre(
movie_id INTEGER REFERENCES Movie (id) NOT NULL,
genre_id INTEGER REFERENCES Genre (id) NOT NULL,
PRIMARY KEY (movie_id, genre_id)
);
package edu.unsw.comp9321.jdbc;
import java.util.HashSet;
import java.util.Set;
public class GenreDTO {
public GenreDTO() {}
public GenreDTO(int id, String genre) {
super();
this.id = id;
this.genre = genre;
}
private int id;
private String genre;
private Set<MovieDTO> movies = new HashSet<MovieDTO>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public Set<MovieDTO> getMovies() {
return movies;
}
public void setMovies(Set<MovieDTO> movies) {
this.movies = movies;
}
}
package edu.unsw.comp9321.jdbc;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OneToMany;
public class MovieDTO implements Comparable {
private int id;
private String title;
private String poster;
private String director;
private String actors;
private String synopsis;
private String release_date;
private int cinema_id;
private Set<GenreDTO> genres = new HashSet<GenreDTO>();
private Set<ReviewDTO> reviews = new HashSet<ReviewDTO>();
private double rating;
public MovieDTO() {
}
public MovieDTO(int id, String title, String poster, String director,
String actors, String synopsis, String release_date, double rating) {
super();
this.id = id;
this.title = title;
this.poster = poster;
this.director = director;
this.actors = actors;
this.synopsis = synopsis;
this.release_date = release_date;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public Set<GenreDTO> getGenres() {
return genres;
}
public void setGenres(Set<GenreDTO> genres) {
this.genres = genres;
}
public Set<ReviewDTO> getReviews() {
return reviews;
}
public void setReviews(Set<ReviewDTO> reviews) {
this.reviews = reviews;
}
public int getCinema_id() {
return cinema_id;
}
public void setCinema_id(int cinema_id) {
this.cinema_id = cinema_id;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
#Override
public int compareTo(Object o) {
MovieDTO other = (MovieDTO) o;
if (this.rating > other.rating) return -1;
if (this.rating < other.rating) return 1;
return 0;
}
}
Yes. There is a better way. Just use a join:
select m from Movie m join m.genres g where g.genre like :genre
or
select m from Genre g join g.movies m where g.genre like :genre
Note that using a like clause is a bit odd. You should use the ID of the genre to uniquely identify it. And if you only have part of a genre's name, you shouldn't assume only one genre contains this genre part.
Also, a DTO is not an entity, and vice-versa. Don't name an entity GenreDTO or MovieDTO. Name it Genre or Movie.