hibernate Autoincrement not set in the database - java

I know that this question has been asked many times but the answers are not perfect.
I would like to set a primary key column with Auto-Increment. Once I create the database, the column is there but AI is not set.
This is a sample code for auto increment
public class ProjectEntity {
private int id;
private String name;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The other problem, is the columns ordering in the database are not the same as the POJO class.
class book{
int ISBN;
String title;
String Author;
String Lang;
int nbPages;
}
In the database, I get: ISBN, LANG, Author, title

Related

How to save with default value using Spring JPA?

Recently I switched into Spring Data JPA and I am wondering how is it possible to save a new object into the database with some default values.
In my example I have to save a book into my database, but, in the owner column, I need to put the value 0.
So, this how I did that with JDBC, and it works amazingly well.
public void save(Book book){
jdbcTemplate.update("INSERT INTO book(name,author,yearOfProduction,owner) VALUES (?, ?, ?, 0)",
book.getName(),book.getAuthor(),book.getYearOfProduction());
}
Now I want to do the same with Spring Data JPA. Here is my save function:
BookService
#Transactional
public void save(Book book)
{
bookRepository.save(book);
}
I have two objects: Person and Book. The relationships are: one person can have many books and one book has one owner. Here are my Person and Book classes:
Book
#Entity
#Table(name = "book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id",nullable = false)
private int id;
#Column(name="name")
#NotEmpty(message = "Book name can't bee empty")
private String name;
#Column(name="author")
#NotEmpty(message = "Author name can't bee empty")
private String author;
#Column(name="yearOfProduction")
#NotNull(message = "Year of production can't bee empty")
#Min(value = 0,message = "year must be more than 1900")
private int yearOfProduction;
#ManyToOne
#JoinColumn(name = "owner_id", referencedColumnName = "id")
private Person owner;
public Book(String name, String author, int yearOfProduction) {
this.name = name;
this.author = author;
this.yearOfProduction = yearOfProduction;
}
public Book(){
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYearOfProduction() {
return yearOfProduction;
}
public void setYearOfProduction(int yearOfProduction) {
this.yearOfProduction = yearOfProduction;
}
}
Person|
#Entity
#Table(name = "person")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
#NotEmpty(message = "Please enter the name")
#Size(min = 1, max = 30, message = "Length must be 2-30 symbols")
//make regex with ФИО;
private String name;
#Column(name = "ageOfBirth")
#Min(value = 0, message = "age of birth must be more than 0")
private int ageOfBirth;
#OneToMany(mappedBy = "owner")
private List<Book> books;
public Person() {
}
public Person(String name, int ageOfBirth) {
this.name = name;
this.ageOfBirth = ageOfBirth;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAgeOfBirth() {
return ageOfBirth;
}
public void setAgeOfBirth(int ageOfBirth) {
this.ageOfBirth = ageOfBirth;
}
}
I guess this is impossible to make with Spring Data JPA? So, I made it with by adding JdbcTemplate and I definitely think it is a hard-coding approach to use Spring DATA and JdbcTemplate together.
It's also unable to make with database. Down below i am using the default definition of postgres and still get null's when create a new book.
https://www.baeldung.com/jpa-default-column-values
create table book(
id int primary key generated by default as identity,
name varchar(250) not null,
author varchar(250) not null,
yearOfProduction int not null,
owner_id int default 0 references person(id)
)
#egeorge answered my question. It is impossible to input 0 into owner table.
Since 0 has a special value, and is not a real person record, there should not be any value in that field. null is the appropriate value for a join column that is not joined to an actual record. You will need to change the logic that interprets 0 as "free" to check for null instead. (I am surprised your database let you do that to begin with. Foreign key constraints will normally reject a value that is not present in the referred table.)

hibernate select data from two tables

I have two tables: authors and books
Author:
#Entity
#Table (name="authors")
public class Author implements java.io.Serializable {
private Integer id;
private String name;
private String lastName;
/*book list*/
private Set<Book> books= new HashSet<Book>(0);
public Author() {
}
public Author(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public Author(String name, String lastName, Set<Book> books) {
this.name = name;
this.lastName = lastName;
this.books = books;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "AUTHOR_ID", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "AUTHOR_NAME", unique = true, nullable = false, length = 10)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "AUTHOR_LASTNAME", unique = true, nullable = false, length = 10)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
Book:
import javax.persistence.*;
#Entity
#Table(name = "books")
public class Book implements java.io.Serializable {
private Integer id;
private String name;
private Author author;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, Author author) {
this.name = name;
this.author = author;
}
#Id
#Column(name = "BOOK_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "BOOK_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "AUTHOR_ID",nullable = false)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
In my book's table I have field with id author. How can I get all books from one author? How Can I solve it?
Must I use HQL or other methods? I am beginner in this.
first you need to the mapping between two entities.
Author class
#OneToMany(mappedBy="author")
private Set<Book> books= new HashSet<Book>(0);
Book class
#ManyToOne
private Author author;
after that you can use a simple criteria query to retrieve the relevant records.
I wont help you with the code here but the logic..
The very first thing you need to do is build a relationship between Author and Books using the annotations #OneToMany or #ManyToOne depending on your structure.
Next use the Author Class Object to retrive the list of Books.

Supported keywords inside method names in Spring JPA

How do I write the method name for the below query:
#Query("SELECT r.skill, r.rating, count(r) FROM AssociateRating r "
+ "where updatedTime = ( select max(updatedTime) from AssociateRating a "
+ "where r.associate = a.associate ) GROUP BY r.skill, r.rating")
List<Object[]> findCountMostRecent();
Please find below the model:
#Entity
#Table(name = "associate_ratings")
public class AssociateRating {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String associate;
#ManyToOne
#JoinColumn(name = "skill_id")
private Skill skill;
private int rating;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_time")
private Date updatedTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAssociate() {
return associate;
}
public void setAssociate(String associate) {
this.associate = associate;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
}
/**
* Skill Model
*/
#Entity
#Table(name = "skills")
public class Skill {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am getting exception when trying to extract records from associate_ratings
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'updatedTime' in 'where clause'
Could you please advise what is wrong here?
Could you also please let me know how do we name Spring JPA findXX methods in such cases?
Indeed there is no 'updatedTime' column in your table.
The column name is 'updated_time', as shown in your #Entity updatedTime variable.
Now in case you want to create method name using JPA keywords I guess it is not possible in your query for several reasons:
You can't select specific columns (r.skill, r.rating, count(r)), but you should select them all.
You can't have nested queries.
There is no GroupBy keyword
You can find all the JPA supported keywords here: 2.3 Query methods
So in your case, you should go for the #Query approach.

Adding foreign key field to a javabean

Consider this regular javabean without ORM/:
// primary key is auto incremented by the database, so I can't add it
public class User {
String name;
int personID; // foreign key
// no args constructor
// getter/setters for fields
}
Is it ok to do this? I personally think it doesn't make sense because there is no reason to manipulate the foreign key through the bean, but I might be wrong. Are there use cases where this is good?
I would normally do it like this.
public class Person {
private final String id;
public Person(String id) {
this.id = id;
}
public Person() {
this.id = UUID.randomUUID().toString();
}
}
and
public class User {
private final String id;
private String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User() {
this.id = UUID.randomUUID().toString();
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
}
Another alternative for User is to make it immutable. In which case it would look something like this.
public class User {
private final String id;
private final String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User(String personId) {
this.personId = personId;
this.id = UUID.randomUUID().toString();
}
public String getPersonId() {
return personId;
}
}
Now the classes can be used in an autoincremented or non-autoincremented way. Basically the option is there for the classes to make their own unique ID or for a unique ID to be passed to it.
One common dilemma that I have seen is when the id does not exist yet the object does. That is the case when the object is created in the program but the ID (which maybe created by the DB when it is inserted) is not assigned to it yet. In that case the bean may look like this.
public class User {
private String id;
private final String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User(String personId) {
this.personId = personId;
}
public String getPersonId() {
return personId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Notice the id is not final and hence the object can exist without the id present and can be added in later if needed
You are better off modelling the objects and their relationships to one another in an object oriented way.
public class User {
private long id;
private Person person;
// .... Removed for clarity
}

hibernate.hbm2ddl.auto=update don't work

I have model. there is this part:
model was mapped by jpa annotations.Everywhere I use fetchType = EAGER. If I load vacancy from database, I have 2 duplicates status_for_vacancy objects.
I use property hbm2ddl.auto = update.
If I make new schema of database and fill data, I haven't duplicates status_for_vacancy objects.
It really?
code:
vacancy:
#Entity
#Table(name = "vacancy")
#XmlRootElement(name="vacancy")
public class Vacancy {
private List<VacancyStatus> statusList = new LinkedList<VacancyStatus>();
#OneToMany(mappedBy = "vacancy", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<VacancyStatus> getStatusList() {
return statusList;
}
public void setStatusList(List<VacancyStatus> statusList) {
this.statusList = statusList;
}
}
status_for_vacancy:
#Entity
#Table(name = "status_for_vacancy")
public class StatusForVacancy extends AbstractStatus {
public StatusForVacancy() {
super();
}
public StatusForVacancy(Integer id, String name) {
super(id, name);
}
}
#MappedSuperclass
#XmlRootElement
public abstract class AbstractStatus {
private Integer id;
private String name;
public AbstractStatus() {
super();
}
public AbstractStatus(String name) {
super();
this.name = name;
}
public AbstractStatus(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column (name ="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
#NotEmpty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
vacancy_status:
#Entity
#Table(name = "vacancy_status")
public class VacancyStatus extends AbstractHistoryStatus {
private Vacancy vacancy;
private StatusForVacancy status;
public VacancyStatus() {
super();
}
public VacancyStatus(Integer id, User author, Date date,
Vacancy vacancy, StatusForVacancy status) {
super(id, author, date);
this.vacancy = vacancy;
this.status = status;
}
#ManyToOne
#JoinColumn(name = "vacancy_id")
public Vacancy getVacancy() {
return vacancy;
}
public void setVacancy(Vacancy vacancy) {
this.vacancy = vacancy;
}
#ManyToOne
#JoinColumn(name = "status_id")
public StatusForVacancy getStatus() {
return status;
}
public void setStatus(StatusForVacancy status) {
this.status = status;
}
}
#MappedSuperclass
public abstract class AbstractHistoryStatus {
private Integer id;
private User author;
private Date date;
public AbstractHistoryStatus() {
}
public AbstractHistoryStatus(Integer id, User author, Date date) {
super();
this.id = id;
this.author = author;
this.date = date;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
#Column(name="creation_date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
It is all mapping code for these entities.
in debugger:
both id==500 ==> hibernate understand, that it is same objects.
I try add all data from old database to new database - I get old error(
I fix cause of appearance of this problem. It appearances if I add record to note table:
I highly recommend you write equals() and hashCode() methods. The standard equals()/hashCode() implement referential equality (do 2 objects reference the same memory location). So if hibernate has 2 of the 'same' object in memory, but they don't reference the same memory location then you will see the object show up twice. But if you implement equals() based on primary key being equal, then even if there are two copies of the same object in memory, Hibernate won't give you duplicates.
See the JPA spec:
2.4 Primary Keys and Entity Identity
Every entity must have a primary key. ... The value of its primary key
uniquely identifies an entity instance within a persistence context
and to EntityManager operations
Also see this SO post.

Categories

Resources