Not able to create oneToMany relationship in Hibernate - java

I am new to Hibernate and I am trying to understand the oneToMany concept. I have created two entities which are Person and Book. A person can borrow many books and a book can only have one person borrowing it. So I have made the following classes
Person.java
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Entity
#Table(name="PERSON")
public class Person {
private static final Logger _logger = LoggerFactory.getLogger(Person.class);
#Id
#GenericGenerator(name="adder", strategy="increment")
#GeneratedValue(generator="adder")
#Column(name="PID")
private Long id;
#Column(name="FIRSTNAME")
private String firstName;
#Column(name="LASTNAME")
private String lastName;
#Column(name="BIRTHDATE")
#Temporal(TemporalType.DATE)
private Date birthDate;
//add genre and books
#OneToMany(orphanRemoval=true, mappedBy="person", cascade=CascadeType.ALL,targetEntity=Book.class)
private Set<Book> listOfBooks = new HashSet<Book>();
public Set<Book> getListOfBooks() {
return listOfBooks;
}
public void setListOfBooks(Set<Book> listOfBooks) {
this.listOfBooks = listOfBooks;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
//add constructor with all the details
}
Book.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Entity
#Table(name="BOOK")
public class Book {
private static final Logger logger = LoggerFactory.getLogger(Book.class);
#Id
#GenericGenerator(name="adder", strategy="increment")
#GeneratedValue(generator="adder")
private Long bookId;
#Column(name="NAME")
private String name;
#Column(name="AUTHOR")
private String author;
#Column(name="PUBLICATION_YEAR")
private int yearOfPublication;
#Column(name="PUBLISHER")
private String publisher;
#ManyToOne()
#JoinColumn(name="PERSON_ID")
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
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 getYearOfPublication() {
return yearOfPublication;
}
public void setYearOfPublication(int yearOfPublication) {
this.yearOfPublication = yearOfPublication;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
HibernateLibraryDaoMain.java
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import se325.project.assignment1.hibernate.domain.Book;
import se325.project.assignment1.hibernate.domain.Person;
public class HibernateLibraryDaoMain {
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Bob");
person.setLastName("Marley");
person.setBirthDate(new Date());
Book book = new Book();
book.setName("Bob Marley book");
book.setAuthor("Lily Marley");
book.setPublisher("Marley Publications");
book.setYearOfPublication(2000);
Book book1 = new Book();
book1.setName("Laura Marley book");
book1.setAuthor("Laura Marley");
book1.setPublisher("Laura Publications");
book1.setYearOfPublication(2005);
person.getListOfBooks().add(book);
person.getListOfBooks().add(book1);
book.setPerson(person);
book1.setPerson(person);
Configuration configuration = new Configuration();
configuration.configure("se325/project/assignment1/hibernate/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.save(book);
session.save(book1);
session.getTransaction().commit();
session.close();
}
}
The problem is that Hibernate does not create a separate Table that illustrates the oneToMany relationship. I can't seem to find the problem. Any help would be appreciated.

I understand where I went wrong. When I have a mappedBy property set, then Hibernate doesn't create a third table but instead it adds to the Entity that has the ManyToOne and joinColumn property. Thanks to all the users that helped :)

Related

Spring Boot "Failed to execute CommandLineRunner Error"

I tried to add One To Many Annotation to my spring boot project, but when I run my project I get "Failed to execute CommandLineRunner " error.
I wanted users in the user's table to have more than one city. So, I tried to add OneToMany Annotation.
You can see the error at the attachment.
User Class
package io.javabrains.springsecurity.jpa.models;
import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="app_user")
public class User {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String userName;
private String password;
private boolean active;
private String role;
private String city;
#OneToMany(targetEntity = UserCity.class,cascade = CascadeType.ALL)
#JoinTable(name="USER_CITY",joinColumns=#JoinColumn(name="m_user_id"),
inverseJoinColumns=#JoinColumn(name="cityId"))
private List<UserCity> usercity;
public User() {
super();
// TODO Auto-generated constructor stub
}
public List<UserCity> getUsercity() {
return usercity;
}
public void setUsercity(List<UserCity> usercity) {
this.usercity = usercity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
User City Class
package io.javabrains.springsecurity.jpa.models;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="user_city")
public class UserCity {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int cityId;
private String cityName;
public UserCity() {
super();
// TODO Auto-generated constructor stub
}
public UserCity(int cityId, String cityName, User mUser) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.mUser = mUser;
}
#ManyToOne
private User mUser;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public User getmUser() {
return mUser;
}
public void setmUser(User mUser) {
this.mUser = mUser;
}
}
User Repository
package io.javabrains.springsecurity.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByUserName(String userName);
}
User City Repository
package io.javabrains.springsecurity.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
public interface CityRepository extends JpaRepository<UserCity,id>{
}
Spring Application Class
package io.javabrains.springsecurity.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
#SpringBootApplication
#EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{
#Bean
public WeatherService ws() {
return new WeatherService ();
}
#Autowired
UserRepository userRepository;
CityRepository cityRepository;
public static void main(String[] args) {
SpringApplication.run(SpringsecurityApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Application Running.");
User adminUser= new User();
UserCity ucity=new UserCity();
UserCity ucity2=new UserCity();
ucity.setCityName("amsterdam");
adminUser.setUserName("Admin");
adminUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
adminUser.setRole("ROLE_ADMIN");
adminUser.setActive(true);
adminUser.setCity("bologna");
ucity.setmUser(adminUser);
userRepository.save(adminUser);
cityRepository.save(ucity);
User newUser= new User();
newUser.setUserName("User");
newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
newUser.setRole("ROLE_USER");
newUser.setActive(true);
newUser.setCity("maribor");
ucity2.setmUser(newUser);
userRepository.save(newUser);
cityRepository.save(ucity2);
}
}
The problem you are encountering, more specifically the NullPointerException at line 54 of your main application, is caused by the fact that the cityRepository is not
instantiated.
Looking through your configuration, I see that you only register the UserRepository with the #EnableJpaRepositories annotation.
Try adding also the CityRepository to the #EnableJpaRepositories, and also specify this bean as a candidate for autowiring( also add #Autowired to this bean, as you did for UserRepository)
For a good practice, following the MVC structure, it would be nice is all your spring repositories, the beans responsible for all CRUD operations with the database to be under the same package

DeleteById Not working in Spring boot JPA Repository

I have two entities- User and Notes. One User can have multiple Notes. I am trying to implement a soft delete for both the tables. For the User table, it is working fine but for Notes table, calling deleteById is not changing the value of the deleted column to true. I tried returning findById(notesId) and it's returning right row but delete is not working.
package com.we.springmvcboot.Model;
import java.util.ArrayList;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import antlr.collections.List;
#Entity
#Table(name="User")
#SQLDelete(sql = "Update User set deleted = 'true' where UserID=?")
#Where(clause = "deleted = 'false'")//FALSE
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long UserID;
#Column(name="emailid")
private String emailID;
#Column(name="deleted")
private String deleted="false";
#OneToMany(mappedBy="user", fetch = FetchType.EAGER,cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Notes> usernotes;
public User() {}
public User(String emailID) {
super();
this.emailID = emailID;
}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public long getUserID() {
return UserID;
}
public void setUserID(long userID) {
UserID = userID;
}
public String getemailID() {
return emailID;
}
public void setemailID(String emailID) {
this.emailID = emailID;
}
public Set<Notes> getUsernotes() {
return usernotes;
}
public void setUsernotes(Set<Notes> usernotes) {
this.usernotes = usernotes;
}
}
package com.we.springmvcboot.Model;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="Notes")
#SQLDelete(sql = "Update Notes set deleted = 'true' where NotesID = ?")
#Where(clause = "deleted = 'false'")
public class Notes {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long NotesID;
#Column(name="title")
private String title;
#Column(name="message")
private String message;
#Column(name="date")
private String date;
#Column(name="deleted")
private String deleted="false";
#Column(name="label")
private int label=1;
#ManyToOne()
#JoinColumn(name = "UserID", nullable = false)
private User user;
public Notes() {}
public Notes(String title, String message, String date, User user, int label) {
super();
this.title = title;
this.message = message;
this.date = date;
this.user = user;
this.label=label;
}
public Notes(long notesID, String title, String message, String date, int label) {
super();
NotesID = notesID;
this.title = title;
this.message = message;
this.date = date;
this.label=label;
}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public int getLabel() {
return label;
}
public void setLabel(int label) {
this.label = label;
}
public long getNotesID() {
return NotesID;
}
public void setNotesID(long notesID) {
NotesID = notesID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public void setUser(User user) {
this.user = user;
}
}
package com.we.springmvcboot.Service;
import com.we.springmvcboot.Model.*;
import com.we.springmvcboot.exception.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import com.we.springmvcboot.Repository.NotesRepository;
import com.we.springmvcboot.Repository.UserRepository;
#Service
public class TodoService {
#Autowired
UserRepository userrepo;
#Autowired
NotesRepository notesrepo;
public Object deleteNote(Map<String, Object> input) throws InvalidInputException, NoteNotFoundException {
long userID;
try {
userID = ((Number) input.get("userID")).longValue();
} catch (Exception e) {
throw new InvalidInputException("Missing UserID");
}
HashMap<String, Object> map = new HashMap<>();
long notesID = ((Number) input.get("notesID")).longValue();
System.out.println(notesID);
if (!notesrepo.findById(notesID).isPresent())
throw new NoteNotFoundException("Invalid Notes ID");
**notesrepo.deleteById(notesID);**
map.put("status", 200);
map.put("message", "Request Successful");
map.put("data", null);
return map;
}
public Object deleteUser(Map<String, Object> input) throws NoteNotFoundException {
HashMap<String, Object> map = new HashMap<>();
long userID;
userID = ((Number) input.get("userID")).longValue();
if (!userrepo.findById(userID).isPresent())
throw new NoteNotFoundException("Invalid User ID");
userrepo.deleteById(userID);
map.put("status", 200);
map.put("message", "Request Successful");
map.put("data", null);
return map;
}
}
Try with #NamedQuery instead of #SQLDelete
or
try with
repo.deleteInBatch(list)

findById() not working on spring boot and Jpa

My main class is :
package com.ashwin.jpafirst;
import com.ashwin.jpafirst.model.Person;
import com.ashwin.jpafirst.reposit.PersonJpaRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class JpafirstApplication implements CommandLineRunner {
private Logger logger= LoggerFactory.getLogger(this.getClass());
#Autowired
PersonJpaRepository personJpaRepository;
public static void main(String[] args)
{
SpringApplication.run(JpafirstApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
logger.info("User id is ",personJpaRepository.findById(2));
}
}
Person.java
package com.ashwin.jpafirst.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="person")
public class Person {
#Id
#GeneratedValue
private int id;
#Column(name="name")
private String name;
private String location;
private Date dateOfBirth;
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 getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Person(int id, String name, String location, Date dateOfBirth) {
this.id = id;
this.name = name;
this.location = location;
this.dateOfBirth = dateOfBirth;
}
public Person() {
}
}
my application properties is:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/jpaintro
spring.datasource.username = root
spring.datasource.password =
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
PersonJpaRepository.java
package com.ashwin.jpafirst.reposit;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.ashwin.jpafirst.model.Person;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public class PersonJpaRepository {
//connects to Databse
#PersistenceContext
EntityManager entityManager;
public Person findById(int id) {
return entityManager.find(Person.class, id);
}
}
I have also data saved in database as:
But when I try to receive the Person object by Id using
logger.info("User id is ",personJpaRepository.findById(2));
I am just getting as :
As Person object needs to print there,but the code is successfully compiling but I am not getting the information regarding the person.My code has no error but it is not retrieving the data.Why is the Person object not printing in the console?

Problems with #ManyToMany Annotation Hibernate - Foreign key has the wrong number of column (should be 3)

I want to add the following database-structure to my Jpa:
CREATE TABLE USER (
id int PRIMARY KEY AUTO_INCREMENT,
firstname varchar(255),
lastname varchar(255)
);
CREATE TABLE PROJECT (
PNUM varchar(255) PRIMARY KEY,
PNAME varchar(255) NOT NULL
);
CREATE TABLE ROLE (
id int PRIMARY KEY AUTO_INCREMENT,
description varchar(255) NOT NULL
);
CREATE TABLE ASSIGNMENT (
user_id int,
project_num varchar(255),
role_id int,
foreign key (user_id) REFERENCES USER(ID),
FOREIGN KEY (project_num) REFERENCES PROJECT(PNUM),
FOREIGN KEY (role_id) REFERENCES ROLE(id),
PRIMARY KEY (user_id, project_num, role_id)
);
So I started off making the three Entities User, Project and Role (See end of this post for full classes). Then I created the Assignment-class for the connection including an #EmbeddedId:
The Assigment class:
package com.demo.example.entity;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
#Entity
public class Assignment {
#EmbeddedId
private AssignmentId id;
public Assignment() {
// TODO Auto-generated constructor stub
}
public AssignmentId getId() {
return this.id;
}
public void setId(AssignmentId id) {
this.id = id;
}
}
The AssignmentId-class
package com.demo.example.entity;
import java.io.Serializable;
import javax.persistence.Embeddable;
#Embeddable
public class AssignmentId implements Serializable {
private Role role;
private Project project;
private User user;
public AssignmentId(Project project, Role role, User user) {
this.project = project;
this.role = role;
this.user = user;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Finally I declared the repository for the Assignment:
package com.demo.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.demo.example.entity.Assignment;
import com.demo.example.entity.AssignmentId;
#Repository
public interface AssignmentRepository extends JpaRepository<Assignment, AssignmentId> {
}
Now upon running a JUnit-Test I run into the following error:
Caused by: org.hibernate.AnnotationException: A Foreign key refering com.demo.example.entity.Assignment from com.demo.example.entity.User has the wrong number of column. should be 3
I have seen quite a few suggestions on what to do but none of them worked (also, most of the time the "should be"-value is 2. Is this even working out with 3?). But I cannot make out why my User-Entity has a wrong number of columns? It provided three in the #JoinTable-Annotation (one join and two inverseJoin-Columns). What did I do wrong?
The classes:
User.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class User {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="user_id")
private int user_id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="user_id")},
inverseJoinColumns = { #JoinColumn(name="pnum"),
#JoinColumn(name="role_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public User() {
}
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public void setId(int id) {
this.user_id = id;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getId() {
return user_id;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
}
Project.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="PROJECT")
public class Project {
#Id
#Column(name="PNUM")
private String pnum;
#Column(name = "PNAME", nullable = false)
private String pname;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="pnum")},
inverseJoinColumns = { #JoinColumn(name="user_id"),
#JoinColumn(name="role_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public Project() {
// TODO Auto-generated constructor stub
}
public Project(String PNUM, String PNAME) {
this.pnum = PNUM;
this.pname = PNAME;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
Role.java:
package com.demo.example.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="ROLE")
public class Role {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="role_id")
private int role_id;
#Column(name = "NAME", nullable = false)
private String name;
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="ASSIGNMENT",
joinColumns = {#JoinColumn(name="role_id")},
inverseJoinColumns = { #JoinColumn(name="user_id"),
#JoinColumn(name="project_id")}
)
private Set<Assignment> assignments = new HashSet<Assignment>();
public Set<Assignment> getAssignments() {
return this.assignments;
}
public Role(String name) {
this.name = name;
}
public int getId() {
return this.role_id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

not-null property references a null or transient value in hibernate

I am getting below exception while executing my code. I am not hibernate expert and just started learning it. Please help. what changes need to be done for successful execution of below code. I have added all the code below.
Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value: hibernate.Student.officeAddress
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:284)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at hibernate.StoreData.main(StoreData.java:44)
Student.java
package hibernate;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table (name="student")
public class Student {
#Id
private int id;
private String firstName;
private String lastName;
private java.util.Date date;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="pincode", column=#Column(name="Home_PIN_Code", nullable=false)),
#AttributeOverride(name="street", column=#Column(name="Home_Street", nullable=false)),
#AttributeOverride(name="city", column=#Column(name="Home_City", nullable=false))
})
private Address homeAddress;
#Embedded
private Address officeAddress;
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column (name="FirstNAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Lob
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal (TemporalType.TIMESTAMP)
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date2) {
this.date = date2;
}
}
Address.java
package hibernate;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="Pincode",nullable=false)
private int pincode;
#Column(name="Street",nullable=false)
private String street;
#Column(name="City",nullable=false)
private String city;
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
StoreData.java
package hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class StoreData {
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction t=session.beginTransaction();
Student e1=new Student();
e1.setId(1);
e1.setFirstName("Majid");
e1.setLastName("Khan");
e1.setDate(new Date());
Address ad1 = new Address();
ad1.setCity("Mumbai");
ad1.setPincode(400059);
ad1.setStreet("Marol Mahrishi Road");
e1.setHomeAddress(ad1);
Student e2=new Student();
e2.setId(2);
e2.setFirstName("Jayada");
e2.setLastName("Bano");
e2.setDate(new Date());
Address ad2 = new Address();
ad2.setCity("Hindaun");
ad2.setPincode(322230);
ad2.setStreet("Islam Colony");
e2.setOfficeAddress(ad2);
session.save(e1);
session.save(e2);
t.commit();
session.close();
System.out.println("successfully saved");
}
}
officeAddress can not be empty when you initialize values to the Student object
Change private int pincode to private Integer pincode as explained here Hibernate Embedded/Embeddable not null exception

Categories