How to make the connection between the mysql database and springboot application - java

I have made a table persons in a schema name test_schema. I have connected the database from DATABASE > CONNECT TO DATABASE in mysql workbench. Then I tried to connect with that but that doesn't seem to work somehow.
BTW I have cloned it from github and trying to run my database in here.
I have tried to see the status but that shows running but the data is not fetching from the database.
application.yml
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/persons
username: root
password: users
jpa:
hibernate.ddl-auto: null
generate-ddl: true
show-sql: true```
UsersRepository.java
package com.techprimers.db.repository;
import com.techprimers.db.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
Users.java
package com.techprimers.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Users {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "token")
private String token;
#Column(name = "name")
private String name;
#Column(name = "post")
private Integer post;
public Users() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPost() {
return post;
}
public void setPost(Integer post) {
this.post = post;
}
}
UsersResources.java
package com.techprimers.db.resource;
import com.techprimers.db.model.Users;
import com.techprimers.db.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping(value = "/rest/users")
public class UsersResource {
#Autowired
UsersRepository usersRepository;
#GetMapping(value = "/all")
public List<Users> getAll() {
return usersRepository.findAll();
}
}
SpringBootMysqldbApplication.java
package com.techprimers.db;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(basePackages = "com.techprimers.db.repository")
#SpringBootApplication
public class SpringBootMysqldbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMysqldbApplication.class, args);
}
}
The result should have been the table elements but instead the Whitelabel Error Page is showing. I don't know what I have been doing wrong since there is nothing much to do. I just modified the code according to my needs but I think I somehow messed with the database connection or I am doing the database connection wrong.
Thanks in advance.

I have come to notice that you said TABLE NAME IS "PERSONS", but in url you have mentioned that as DB name
jdbc:mysql://${DB_SERVER_NAME}:${DB_PORT}/${DB_DATABASE}:currentSchema=${DB_SCHEMA};
which is jdbc:mysql://localhost:3306/<db-name>
Check that once

Unfortunately I can't comment yet but I think your database enforces ssl by default Since MySQL 5.7.5, but it is not obligatory for clients by default. Check this url please jdbc:mysql://localhost:3306/persons?useSSL=false
As Avi mentioned, If your database is test_schema write it in the url instead of persons
And please, provide errors and exceptions right in the question if there any
Link how to handle ssl in mysql
Stackoverflow spring and mysql ssl question

Related

Hibernate Error : attempted to assign id from null one-to-one property. Why?

I am trying my hands at Hibernate Relation Mapping(OneToOne, etc) exercises using Spring Boot. Before you ask, I have already consulted this link : [https://stackoverflow.com/questions/11104897/hibernate-attempted-to-assign-id-from-null-one-to-one-property-employee]. I understand that the weak entity needs to have a ref to the parent entity, but I am not able to figure out, why I need to do that explicitly in Person class constructor?
The Codes are as follows.
SpringApplication:
package com.OneToOne.OneToOneMappingPractice;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
ApplicationContext applContext = SpringApplication.run(App.class, args);
String[] beanNames = applContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for(String beanName : beanNames)
System.out.println(beanName);
}
}
CRUDController.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
public class CRUDController
{
private static int randomNumber=(int) Math.random();
#Autowired
private CRUDControllerRepository repository;
#GetMapping(value="/add")
public void add()
{
Person person = new Person("Person"+randomNumber, "Street"+randomNumber, randomNumber);
repository.save(person);
randomNumber+=1;
}
#GetMapping(value="/getAll")
public List<Person> getAll()
{
return repository.findAll();
}
#DeleteMapping(value="/deleteAll")
public void deleteAll()
{
repository.deleteAll();
}
}
Person.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
public class Person
{
private String name;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int Id;
#OneToOne(mappedBy="person", cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Address address;
public Person() {}
public Person(String name, String streetName, int house_number)
{
super();
this.name = name;
this.address=new Address();
this.address.setStreetName(streetName);
this.address.setHouse_number(house_number);
//this.address.setPerson(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
#Entity
public class Address {
#Id
#Column(name="user_id")
private int Id;
private int house_number;
private String streetName;
#OneToOne
#MapsId
#JoinColumn(name = "user_id")
private Person person;
public Address(){}
public int getHouse_number() {
return house_number;
}
public void setHouse_number(int house_number) {
this.house_number = house_number;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
// public Person getPerson() {
// return person;
// }
public void setPerson(Person person) {
this.person = person;
}
}
CRUDControllerRepository.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public interface CRUDControllerRepository extends JpaRepository<Person, Integer>
{
Person save(Person person);
void deleteAll();
List<Person> findAll();
}
Following are my questions :
As you can see, in the Person class parameterized constructor, I have commented out the line : this.address.setPerson(this);. If I keep this line commented out, I get the exception : "attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]". If I remove the comment syntax, it works perfectly. Why do I need to explicitly do this? Isn't the #OneToOne annotation supposed to take care of these references by itself?
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error page for request [/getAll] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException".
Why cant Hibernate itself determine that it needs to stop at that boundary itself, instead of fetching the Parent Object again?
Am I missing something here about these mapping annotations, or anything else?
1- As you can see, in the Person class parameterized constructor, I
have commented out the line : this.address.setPerson(this);. If I keep
this line commented out, I get the exception : "attempted to assign id
from null one-to-one property
Hibernate will not set it explicitly because it does not know to which person this address belongs to you need to specify that explicitly.
The purpose of #OneToOne is to tell hibernate where to get the rest of the data when it is already mapped.
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error
page for request [/getAll] and exception [Could not write JSON:
Infinite recursion (StackOverflowError); nested exception is
com.fasterxml.jackson.databind.JsonMappingException". Why cant
Hibernate itself determine that it needs to stop at that boundary
itself, instead of fetching the Parent Object again?
The exception is caused by Jackson serializer and not from hibernate.
you can look at the examples here to see how it is fixed https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion.

How can I reach database as json value when i request on my local browser?

Note: This is a project which has a connection with database on other tables. I just made a new table, but i must have something wrong in my codes, because i cant get what i want.
I have a City table, and this table has 3 columns, named id, name, city_id. And i imported a csv file, so when i query, I can see some data.
I wrote Entity, Repository, Controller, and Service, in Java on Eclipse
What should I do? For example, when i search like localhost:8181/mfc/city/getAllCities that should give me all the cities as json
Could you tell me what i should add?
City.java
package com.mfc.entity;
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
#Table(name="city")
public class City{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="city_name")
String cityName;
#Column(name="city_id")
int cityId;
public City() {
super();
}
public City(int id, String cityName, int cityId) {
super();
this.id = id;
this.cityName = cityName;
this.cityId = cityId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
CityController.java
package com.mfc.admin.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mfc.admin.service.CityService;
import com.mfc.entity.City;
#RestController
#RequestMapping("/city")
public class CityController {
private static final Logger logger = LogManager.getLogger(CityController.class);
#Autowired
CityService cityService;
#RequestMapping(value="/getAllCities", method=RequestMethod.GET, headers = "Accept=application/json")
public List getCities() {
logger.trace("CityController: getAllCities begins");
List listOfCities = cityService.getAllCities();
logger.trace("CityController: getAllCities ends");
return listOfCities;
}
#RequestMapping(value="/getCity/{id}", method=RequestMethod.GET, headers = "Accept=application/json")
public City getCityById(#PathVariable int id) {
return cityService.getCity(id);
}
}
CityService.java
package com.mfc.admin.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mfc.entity.City;
import com.mfc.repository.CityRepository;
#Service("cityService")
public class CityService {
#Autowired
CityRepository cityDTO;
#Transactional
public List getAllCities() {
return cityDTO.getAllCities();
}
#Transactional
public City getCity(int id) {
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
}
}
CityRepository.java
package com.mfc.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mfc.entity.City;
public interface CityRepository extends JpaRepository<City, Integer>{
List getAllCities();
City getCity();
}
In the CityService you call the CityRepository like this
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
But no such method is defined in the CityRepository. Try using this line return cityDTO.findById(id).get();
You can't see the method findById(Integer id) in the CityRepository, but it is there, because the CityRepository extends JpaRepository<City, Integer>. Find some Spring Data tutorial to know what's really going on in here, long story short the Spring Data is able to generate a lot of standard methods for you.
The method cityDTO.findById(id) returns Optional<City>, not City. To get the instance of City, just add '.get()' method, as it is in the example. It should work for you if city exists in the database. For proper work with Optional find some tutorial. It is a wrapper of an object that may or may not be present, detailed explanation is out of the scope of this answer.
maybe you can try to set up message converter manualy, google MappingJackson2HttpMessageConverter and you'll know what to do.

REST API is always throwing 404 error in Spring boot maven multimodule project with H2 database

I am new to Spring boot and I have created a multi-module project(maven) with spring boot. And I created some REST APIs and connected to H2 database.
The database is connected successfully and able to run in localhost.
This is my project tree.. User-Management is parent and core, serverAPI are child modules. And I have created packages for each module and added the relevant classes.
I have tried everything I know and searched google for like 5 days but nothing worked for me. I have included every code I wrote here. Please help me to find what the issue is.
(I am using intellij idea 2020.3 ultimate)
User.java
package com.hms.usermanagement.core.model;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "full_name")
private String fullName;
#Column(name = "email")
private String email;
public User() {
}
public User(long id, String fullName, String email) {
this.id = id;
this.fullName = fullName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}}
UserRepository
package com.hms.usermanagement.core.repository;
import com.hms.usermanagement.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
Application
package com.hms.usermanagement.serverAPI.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.run(args);
}}
UserController
package con.hms.usermanagement.serverAPI.controller;
import com.hms.usermanagement.core.model.User;
import com.hms.usermanagement.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserRepository userRepository;
//Create Users
#PostMapping("/user")
public User createUser( #Validated #RequestBody User user){
return userRepository.save(user);
}
//View all Users
#GetMapping("/users")
public List<User> getAllUsers(){
return userRepository.findAll();
}
//Update Users
#PutMapping("/users/{id}")
public ResponseEntity <User> updateUser(#PathVariable(value = "id") long userId , #RequestBody User userDetails){
Optional<User> user = userRepository.findById(userId);
if(user.isPresent()){
User _user = user.get();
_user.setFullName(userDetails.getFullName());
_user.setEmail(userDetails.getEmail());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
}else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
//Delete Users
#DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(#PathVariable(value = "id") long userId){
userRepository.findById(userId);
userRepository.deleteById(userId);
return ResponseEntity.ok().build();
}
application.properties
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enable H2 console
spring.h2.console.enabled=true
#custom H2 console
spring.h2.console.path=/h2
schema-h2.sql
CREATE TABLE users (id long PRIMARY KEY AUTO_INCREMENT, full_name VARCHAR(30), email VARCHAR(50));
I have tried using both these 2 urls
Even "id" field is auto generated but I tried to add id also using postman.. But still getting the same error
Your Sprint boot runner class, Application class is under com.hms.usermanagement.serverAPI.application package, so Spring boot will only scan the components under com.hms.usermanagement.serverAPI.application. So your core and web components are not recognized by Spring boot.
To solve the issue try to move Application.java class under com.hms.usermanagement.
Or you can customize the component scan by adding#ComponentScan annotation to Application.java class:
#SpringBootApplication
#ComponentScan(basePackages = "com.hms.usermanagement")
I did a new maven: mvn clean verify of the project and the issue was solved.
Remove #Validated and try #Valid as below
Calling with [LOCALHOST]:[PORT]/api/user
//Create Users
#PostMapping("/user")
public User createUser(#RequestBody #Valid User user){
return userRepository.save(user);
}

Spring Data neo4j - Id generation strategies

I'm working on an example project in which I have a model class Movie and I want this movie to have a UUID as the identifier.
I tried the following code.
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.hibernate.annotations.GenericGenerator;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.springframework.data.annotation.Id;
import javax.persistence.GeneratedValue;
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
#NodeEntity
public class Movie {
#Id #GeneratedValue(generator = "uuid")
#GenericGenerator(name="uuid", strategy="uuid2")
private String id;
private String title;
private int released;
private String tagline;
#Relationship(type = "ACTED_IN", direction = Relationship.INCOMING)
private List<Role> roles = new ArrayList<>();
public Movie() {
}
public Movie(String title, int released, String tagline) {
this.title = title;
this.released = released;
this.tagline = tagline;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public int getReleased() {
return released;
}
public String getTagline() {
return tagline;
}
public Collection<Role> getRoles() {
return roles;
}
public void addRole(Role role) {
this.roles.add(role);
}
}
This code is generating an error.
org.neo4j.ogm.exception.MappingException: No identity field found for class: movies.spring.data.neo4j.domain.Movie
here is the reference I used to write this code
I am using neo4j-ogm-core:2.1.3
I didn't understand what was in the reference fully.
but I needed to import Hibernate to use #GenericGenerator
Question:
How can I use UUID inside my model. knowing that I'm using Spring Data?
Note: I am new to Neo4j and Spring. I am having difficulties asking the proper questions.
Alternatively, you can use the GraphAware Neo4j UUID. According the library REDME file:
GraphAware UUID is a simple library that transparently assigns a UUID
to newly created nodes and relationships in the graph and makes sure
nobody can (accidentally or intentionally) change or delete them.
Simply download GraphAware Neo4j Framework and GraphAware Neo4j UUID .jar files to /plugins directory, modify few lines in neo4j.conf file and restart Neo4j. After it, UUIDs will be assigned to each node / relationships created in the Neo4j graph.
This approach does not depends on Spring.

save working but persist not working in hibernate 4.1.1

I am trying to save data usign hsqldb and I am using hibernate 4.1.4.Final. My problem is I want to save data using persist but when I tried to do it's showing following error:
org.hibernate.PersistentObjectException: detached entity passed to persist: main.java.entity.Advocate
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:835)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:828)
at org.hibernate.engine.spi.CascadingAction$7.cascade(CascadingAction.java:315)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:423)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:264)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:844)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:819)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:823)
at main.java.service.LegalService.registerCase(LegalService.java:46)
at main.java.tester.Tester.registerCase(Tester.java:52)
at main.java.tester.Tester.main(Tester.java:28)
But when I use save method it worked.So I want to know how persist and save makes difference? and my entity classes are serialized.How to solve this persist error.
Here is my class
package main.java.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import main.java.businessTier.CaseTO;
import main.java.entity.Advocate;
import main.java.entity.Case;
public class LegalService {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
public int registerCase(CaseTO caseTO) {
try
{
Session session;
session=sessionFactory.openSession();
session.beginTransaction();
Case c = new Case();
Advocate a = new Advocate();
a.setAdvocateId(caseTO.getAdvocateId());
c.setAdvocate(a);
c.setClientAge(caseTO.getClientAge());
c.setClientName(caseTO.getClientName());
c.setDate(caseTO.getDate());
c.setDescription(caseTO.getDescription());
session.persist(c);
session.getTransaction().commit();
return c.getCaseNo();
}
catch(Exception e){
e.printStackTrace();
return 0;
}
}
}
Here are my entity class
Advocate.java
package main.java.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
#Entity
#Table(name="Db_Advocate")
#DynamicInsert(value=true)
#DynamicUpdate(value=true)
public class Advocate {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="advocateId")
private Integer advocateId;
#Column(name="name")
private String name;
#Column(name="age")
private Integer age;
#Column(name="category")
private String category;
#Column(name="court")
private String court;
#Column(name="city")
private String city;
public Integer getAdvocateId() {
return advocateId;
}
public void setAdvocateId(Integer advocateId) {
this.advocateId = advocateId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCourt() {
return court;
}
public void setCourt(String court) {
this.court = court;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Case.java
package main.java.entity;
import java.util.Date;
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.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
#Entity
#Table(name="DB_CASE")
#DynamicInsert(value=true)
#DynamicUpdate(value=true)
public class Case {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer caseNo;
#JoinColumn(name="advocateId")
#ManyToOne(cascade=CascadeType.ALL)
private Advocate advocate;
private String clientName;
private Integer clientAge;
private String description;
private Date date;
public Integer getCaseNo() {
return caseNo;
}
#Column(name="caseNo")
public void setCaseNo(Integer caseNo) {
this.caseNo = caseNo;
}
public Advocate getAdvocate() {
return advocate;
}
public void setAdvocate(Advocate advocateId) {
this.advocate = advocateId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public Integer getClientAge() {
return clientAge;
}
public void setClientAge(Integer clientAge) {
this.clientAge = clientAge;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate() {
return date;
}
#Column(name="data",nullable=true)
public void setDate(Date date) {
this.date = date;
}
}
First you need to understand behaviour of persist().
Below are the links that will help you understand the behaviour
Whats the difference between persist() and save() in Hibernate?
http://javarevisited.blogspot.in/2012/09/difference-hibernate-save-vs-persist-and-saveOrUpdate.html
Now in order to solve this problem in your code .. use merge() instead of persist().
Why persist() gave the exception
persist() does not work for detached objects .You need to know how hibernate determines whether an object is detached or not.
UPDATE
Why the identifier generation strategy auto solved your problem
As i mentioned above that you need to understand the rules by which hibernate identifies whether an object is detached or transient. Below are the rule
If the the entity has a null value for identifier or the version attribute is null it is considered as transient other wise detached.
If you use auto-generated identifiers, and the identifier is not null, then Hibernate considers it as a detached entity.
If you are using assigned identifier strategy then hibernate will issue a fetch to determine whether the identifier exists in db based on that your entity will be either transient or detached.
Now that being said .. we analyse your code.
In your code you have Advocate entity whose identifier strategy is IDENTITY.In the below code
Case c = new Case();
Advocate a = new Advocate();
a.setAdvocateId(caseTO.getAdvocateId());
You are setting the identifier property of Advocate instance manually.At the time of flush when transaction commits ,hibernate will see that the identifier generation strategy is IDENTITY and the identifier value is set in the advocate instance hence it will conclude that the entity instance is detached (this is from the rule 1 described above).And hence the persist() method gave exception for the advocate instance as it is deemed to be detached from hibernate.
From rule 2 we can say that your code will not work just by changing the generation strategy to auto.You might have done some other changes.
I have tried your code on my system it is giving the same exception even if i change the generation strategy to auto which is in consistent with the rules
You might be doing something different in your code .. please check and update.
Please also post the identifier that you are setting in the advocate and the actual identifier generated for that advocate in database with auto generation strategy, that might be helpful
Please Add below code at id
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Then persist will work

Categories