findById() not working on spring boot and Jpa - java

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?

Related

How to get selective columns in Export Csv in Spring boot

I am new to spring boot and i am creating a spring boot app to generate csv files from data fetched from database .I'm using h2 database for it and want to get selective columns from my entity-id,amount
entity class:
package com.reports.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity(name="reportDetails")
#Table(name = "reports")
public class Report {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="amount")
private int amount;
public Report() {
super();
}
public Report(int id, String name, String email, int amount) {
super();
this.id = id;
this.name = name;
this.email = email;
this.amount = amount;
}
public long 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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
main class:
package com.reports;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;
#SpringBootApplication
public class ExportCsvApplication implements CommandLineRunner {
#Autowired
ReportsRepository reportsRepository;
public static void main(String[] args) {
SpringApplication.run(ExportCsvApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Report> reports = new ArrayList<>();
// create dummy employees
reports.add(new Report(1,"roy","roy#123.com",2500));
reports.add(new Report(2,"joy","joy#123.com",2500));
reports.add(new Report(3,"soy","soy#123.com",2500));
reports.add(new Report(4,"moy","moy#123.com",2500));
reports.add(new Report(5,"noy","noy#123.com",2500));
reportsRepository.saveAll(reports);
}
}
repository :
package com.reports.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.reports.entities.IReport;
import com.reports.entities.Report;
#Repository("reportsRepository")
public interface ReportsRepository extends JpaRepository<Report,Long>{
}
Service class:
package com.reports.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.reports.entities.IReport;
import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;
#Transactional
#Service
public class ReportsService {
#Autowired
ReportsRepository reportsRepository;
public List<Report> fetchAll() {
return (List<Report>) reportsRepository.findAll();
}
}
Controller:
package com.reports.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.reports.entities.Report;
import com.reports.services.ReportsService;
#RestController
public class ReportsController {
#Autowired
ReportsService reportsService;
#GetMapping("/export-report")
public void exportCSV(HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// create a csv writer
StatefulBeanToCsv<Report> writer = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false).build();
// write all employees to csv file
writer.write(reportsService.fetchAll());
}
}
I want to know what would be the best method to incorporate for it i tried query but faced errors.Please let me know how do i get this done
This is more of being related to the opencsv library than Spring or Spring Boot itself.
When constructing the StatefullBeanToCsvBuilder, you should use the withIgonreField builder property to instruct the final StatefullBeanToCsv on which fields to ignore for which types.
Say you want only the id and amount fields out of your Report entity, you can achieve this as follows:
#RestController
public class ReportsController {
#Autowired
ReportsService reportsService;
#GetMapping("/export-report")
public void exportCSV(HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Report> builder = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Report.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Report> writer = builder.build();
// write all employees to csv file
writer.write(reportsService.fetchAll());
}
}

Jpa Repository instance is null in service layer

So i want to save the data with the help of JPA repository but when i autowired it is giving me null.
I don't know what else to do in here I have also tried with #EnableJPARepository annotation still no help. So here are the classes i am using. I want to save the data that is published by kafka so is it best to create a seperate function or can i put save to db function in consume json?
Repository
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import org.springframework.data.repository.CrudRepository;
public interface KafkaRepository extends CrudRepository<KafkaEntity,Long> {
}
KafkaEntityClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import javax.persistence.*;
#Entity
#Table(name = "messages")
public class KafkaEntity {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String userName;
#Column(nullable = false)
private String userMessage;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
ServiceClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import com.prateek.addaKafka.addaKafka.model.UserPublishModel;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
#Service
public class KafkaListenerService {
#Autowired
KafkaRepository kafkaRepository;
#KafkaListener(topics = "NewTopic",groupId = "group_json",
containerFactory = "userKafkaListenerFactory")
public UserPublishModel consumeJson(UserPublishModel userPublishModel) {
return userPublishModel;
}
public void saveToDB(UserPublishModel userPublishModel){
ModelMapper modelMapper=new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
KafkaEntity kafkaEntity=modelMapper.map(userPublishModel, KafkaEntity.class);
kafkaRepository.save(kafkaEntity);
}
}
MainClass
package com.prateek.addaKafka.addaKafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
public class AddaKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(AddaKafkaApplication.class, args);
}
}

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

issue with interface io.javabrains.repository.DepartmentRepository

I was trying to build CRM for university.But when I tried to auto built table within the hibernate,it displays me the following error:
Not managed type interface io.javabrains.repository.DepartmentRepository
I just tried to add Repository annotation to every other Repo classes but no results were achieved
Department Category.class
package io.javabrains.Entities;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
#Data
#EqualsAndHashCode(exclude="Student")
#Entity
#Table(name="department")
public class DepartmentCategory {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public int getId() {
return id;
}
public DepartmentCategory(int id, String name, Set<Student> students) {
super();
this.id = id;
this.name = name;
this.students = students;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
private String name;
#OneToMany(mappedBy = "departmentCategory",cascade = CascadeType.ALL)
private Set<Student>students;
}
DepartmentRepository.class
package io.javabrains.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface DepartmentRepository extends JpaRepository<DepartmentRepository, Integer> {
}
CrmSchoolApplicaton.class
package io.javabrains;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
#SpringBootApplication
public class CrmSchoolApplication {
public static void main(String[] args) {
SpringApplication.run(CrmSchoolApplication.class, args);
}
}
...............
try to change your JpaRepository :
public interface DepartmentRepository extends JpaRepository<Department, Integer>
instead of
public interface DepartmentRepository extends JpaRepository<DepartmentRepository, Integer>

Not able to create oneToMany relationship in Hibernate

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 :)

Categories