Hibernate - Custom Id Generation - java

I am persisting entity to mysql database. my requirement is to store id as BR01 , BR02 ,... etc. instead of storing as 1,2,.. etc.
how can i store id as BR01,BR02,.. etc?
I know sequence is not supported in mysql database.
my entity class is as follows :
package com.kabira.hrm.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
#Entity
#Table(name="branch")
public class Branch
{
private Long id;
private String country;
private String state;
private String city;
private String address;
private String phoneNumber;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getPhoneNumber()
{
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
#Override
public String toString()
{
return "Branch [id=" + id + "]";
}
}

You can extend org.hibernate.id.enhanced.SequenceStyleGenerator and use it with annotations #GenericGenerator.

You may want to check out a solution like this. Hibernate: How specify custom sequence generator class name using annotations? This way you make your own key generator.

Write custom generator class and put the logic there to fetch max id from db and you would parse number from that id and convert that number into an integer and make increment to that number and again concat with your required prefix and return concatenated value.
write this logic here
import org.hibernate.id.IdentifierGenerator;
public class MyGenerator implements IdentifierGenerator {#
Override
public Serializable generate(SessionImplementor session, Object object){
// your logic comes here.
}
}

Related

.DefaultHandlerExceptionResolver Im getting this error while uploading the data please help me out in this project its working properly on server

The contact class as an entity that would be linked with address class
package asmt1.demo.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
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.ManyToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import asmt1.demo.dto.UserStatus;
//#Entity annotation specifies that the class is an entity and is mapped to a database table.
//#Table annotation specifies the name of the database table to be used for mapping
#Entity
#Table(name="Contactdetail")
public class Contact {
//#Id is used to specify the primary key
#Id
//Generated value is used to generate pk value ie. id to be autogenerated and assign identity column(id)
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
//#column is used to specify the column condition
//#Column( unique = true)
private String firstName;
private String lastName;
//#Column(unique = true)
private long contactNo;
private String mailId;
//list of named constant ie. status
#Enumerated(EnumType.STRING)
private UserStatus status;
//it is used to create one-to-one relationship between the contact and address table
//fetch type.lazy tells Hibernate to only fetch the related entities from the database when you use the relationship
#ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinTable(name="conadd",
joinColumns = {#JoinColumn(name="id")},
inverseJoinColumns = {#JoinColumn(name="addid")})
//To handle the problem related to the serialization of the model using Jackson API when the model attributes have a lazy loading defined,
//we have to tell the serializer to ignore the chain or helpful garbage that Hibernate adds to classes, so it can manage lazy loading of data by declaring #JsonIgnoreProperties
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private Set<Address> address=new HashSet<>();
//generate getters,setters, toString() and constructor using fields
public Contact() {}
public Contact(String firstName, String lastName, long contactNo, String mailId, UserStatus status,
Set<Address> address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.contactNo = contactNo;
this.mailId = mailId;
this.status = status;
this.address = address;
}
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
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 long getContactNo() {
return contactNo;
}
public void setContactNo(long contactNo) {
this.contactNo = contactNo;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
#Override
public String toString() {
return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", contactNo=" + contactNo
+ ", mailId=" + mailId + "]";
}
}
the address class which is the entity
package asmt1.demo.entity;
import java.util.HashSet;
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.ManyToMany;
import javax.persistence.Table;
//#Entity annotation specifies that the class is an entity and is mapped to a database table.
//#Table annotation specifies the name of the database table to be used for mapping
#Entity
#Table(name="addressDetail")
public class Address {
//#Id is used to specify the primarykey
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long addid;
private String street1;
private String street2;
private long zipcode;
private String city;
private String state;
private String Country;
//mappedby is used to specify to relationship
#ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "address")
private Set<Contact> contact=new HashSet<>();
//generate getters,setters, toString() and constructor using fields
public long getId() {
return addid;
}
public Set<Contact> getContact() {
return contact;
}
public void setContact(Set<Contact> contact) {
this.contact = contact;
}
public void setId(long id) {
this.addid = id;
}
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
public long getZipcode() {
return zipcode;
}
public void setZipcode(long zipcode) {
this.zipcode = zipcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public Address(String street1, String street2, long zipcode, String city, String state, String country) {
super();
this.street1 = street1;
this.street2 = street2;
this.zipcode = zipcode;
this.city = city;
this.state = state;
Country = country;
}
public Address() {}
}
a request class where I was calling both for data uploading
package asmt1.demo.dto;
import java.util.HashSet;
import java.util.Set;
import asmt1.demo.entity.Address;
import asmt1.demo.entity.Contact;
public class AddressReq {
private Set<Address> address=new HashSet<>();
private Set<Contact> contact=new HashSet<>();
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
public Set<Contact> getContact() {
return contact;
}
public void setContact(Set<Contact> contact) {
this.contact = contact;
}
public AddressReq(Set<Address> address, Set<Contact> contact) {
super();
this.address = address;
this.contact = contact;
}
public AddressReq() {}
#Override
public String toString() {
return "AddressReq [address=" + address + ", contact=" + contact + "]";
}
}
enum class for status
package asmt1.demo.dto;
//constant value for userstatus class
public enum UserStatus {
ACTIVE,INACTIVE
}
controller class
package asmt1.demo.controller;
import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import asmt1.demo.converter.ContactConverter;
import asmt1.demo.dto.AddressReq;
import asmt1.demo.dto.ContactDto;
import asmt1.demo.entity.Contact;
import asmt1.demo.repository.AddressRepo;
import asmt1.demo.repository.ContactRepo;
//#restcontroller is used for restful services
#RestController
//#RequestMapping is used for creating baseurl for controller will be used
#RequestMapping("/contact")
public class ContactController {
//#Autowired will search the object of class
#Autowired
private ContactRepo ctrepo;
#Autowired
private AddressRepo addrepo;;
#Autowired
private ContactConverter converter;
//#Requestbody is used to map/bind methods with pojo pr value to return value to the web
//#postmapping is used to add data to database from web
#PostMapping("/add")
public List<Contact> newcontact(#RequestBody AddressReq req) {
return ctrepo.saveAll(req.getContact());
}
//#getmapping is used to get the details/records from database on web page
#GetMapping("/contactlist")
public List<Contact> getcontactlist(){
return ctrepo.findAll(Sort.by(Sort.Direction.ASC, "firstName","lastName"));
}
#GetMapping("/contactdto")
public List<ContactDto> getcontactlistdto(){
List<Contact> findAll=ctrepo.findAll();
return converter.entitytodto(findAll);
}
#GetMapping("/contactlist/{id}")
public ResponseEntity<Contact> get(#PathVariable Long id) {
try {
Contact contact = ctrepo.getOne(id);
return new ResponseEntity<Contact>(contact, HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<Contact>(HttpStatus.NOT_FOUND);
}
}
#GetMapping("/contactdto/{id}")
public ContactDto getbyid(#PathVariable Long id) {
Contact orElse=ctrepo.findById(id).orElse(null);
return converter.entitytodto(orElse);
}
#GetMapping("/orderlist")
public List<Contact> getcontactlistbyorder(){
return ctrepo.findAllByOrderByIdDesc();
}
#PostMapping("/save")
public ContactDto savedto(#RequestBody ContactDto dto) {
Contact contact=converter.dtotoentity(dto);
contact=ctrepo.save(contact);
return converter.entitytodto(contact);
}
//#deletemapping is used to delete the records/details from database by web page
#DeleteMapping("/delete/{id}")
public String deletebyid(#PathVariable long id){
if (ctrepo.findById(id)==null) {
return "Id not found.....Please enter correct id";
}
ctrepo.deleteById(id);
return "Successfully deleted "+id;
}
//#putmapping is used to change/update the records/details in database by web page
#PutMapping("/edit")
public List<Contact> editcontactbyid(#RequestBody AddressReq req ){
return ctrepo.saveAll(req.getContact());
}
}
here is the Json format which I was uploading the data but its showing me error that
at [Source: (PushbackInputStream); line: 1, column: 2]]
2021-05-04 12:57:07.799 WARN 876 --- [nio-9090-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of java.util.HashSet<asmt1.demo.entity.Contact> out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.HashSet<asmt1.demo.entity.Contact> out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 13] (through reference chain: asmt1.demo.dto.AddressReq["contact"])]
{"contact":{
"firstName":"tomu",
"lastName":"shawn",
"contactNo":9124245,
"mailId":"ggia#gmail.com",
"status":"INACTIVE",
"address":{
"street1":"A/wing-24",
"street2":"plotno-4",
"city":"Mumbai",
"state":"Maharashtra",
"country":"India",
"zipcode":705
}}}
In your AddressReq class contact is set that is collection but in your pay load you are sending an object which should be collection of object.
Based on the AddressReq class the pay load should be
{["contact":{
"firstName":"tomu",
"lastName":"shawn",
"contactNo":9124245,
"mailId":"ggia#gmail.com",
"status":"INACTIVE",
"address":{
"street1":"A/wing-24",
"street2":"plotno-4",
"city":"Mumbai",
"state":"Maharashtra",
"country":"India",
"zipcode":705
}
}]
}
or if your request is always single entry of contact then you can change the contact property to single instance not the collection of Contact instance.

Springboot Hibernate read data from existing table on SQL Server

I have an existing Table in SQL Server.
CREATE TABLE [dbo].[STUDENTS](
[ID] [int] NOT NULL,
[FIRSTNAME] [varchar](50) NOT NULL,
[LASTNAME] [varchar](50) NOT NULL,
[EMAIL] [varchar](100) NOT NULL,
[AGE] [int] NOT NULL,
[ADDRESS] [varchar](3000) NOT NULL,
PRIMARY KEY (ID)
);
I have created this entity in JAVA to me able to extract data using Hibernate.
package com.My_task_be.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTS")
public class Student {
#Id
#Column(name = "ID")
public int id;
#Column(name = "FISRTNAME")
public String firstName;
#Column(name = "LASTNAME")
public String lastName;
#Column(name = "EMAIL")
public String email;
#Column(name = "AGE")
public int Age;
#Column(name = "ADDRESS")
public String Address;
public int getId() {
return id;
}
public void setId(int 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
This is the repository
#Repository
public interface StudentRepository extends CrudRepository<Student, Integer>{
List<Student> findAll();
}
This is the controller
#RestController
public class AppController {
#Autowired
private StudentRepository studentRpository;
#GetMapping("/getAllStudents")
public List<Student> getAllStudents(){
return studentRpository.findAll();
}
#GetMapping("/helloWorld")
public String helloWorld(){
return "Hello World!";
}
}
When i run http://localhost:8080/getAllStudents
I get Invalid column name 'fisrtname'.
I dont want hibernate to create a new table I just want it to read from an existing table.
And I have specified the Column names but still it did not work.
Any ideas?
You have a typo in FISRTNAME. It is FIRSTNAME, change as below
#Column(name = "FIRSTNAME")
public String firstName;

SpringBoot-Hibernate-Mysql id primary key value sequence is shared in all of my domain using #GeneratedValue

I have two classes/domains (Person) and (Account), they both have id field with #GeneratedValue(strategy = GeneratedType.AUTO) or any other GeneratedType, but saving domains cause them to share the sequence of Primary key.
When I save a person domain, it will use id=1, then saving a account will use id=2 even though they are completely different domain, I don't want this, been searching for quite a while but I don't know the keyword to search.
EDIT: Changed Pet to Account
Im using Spring Boot 2.0.4.RELEASE with spring-boot-starter-data-jpa.
MySql is 8.0
I have a mappedSuperclass Domain Class, but even though I put Id separately per class, it still same behavior..
Domain Class
package com.myband.band.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public abstract class Domain {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
Person Class
package com.myband.band.domain;
import javax.persistence.Entity;
#Entity
public class Person extends Domain {
private String firstName;
private String lastName;
private String nickName;
private int age;
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 String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Account Class
package com.myband.login.domain;
import javax.persistence.Entity;
import com.myband.band.domain.Domain;
#Entity
public class Account extends Domain {
private String username;
public Account() {
}
public Account(String username) {
super();
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
When you are using #GeneratedValue(strategy = GenerationType.AUTO), your table is not created with the auto increment feature in mysql. If you want to use that feature for the primary key, use #GeneratedValue(strategy = GenerationType.IDENTITY) instead.
Please refer Gergely Bacso's answer to understand how GenerationType.AUTO works.
You can fix this by changing your ID definition to:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pet_generator")
#SequenceGenerator(name="pet_generator", sequenceName = "pet_seq")
What currently happening to you is:
You defined "AUTO" ID generation logic, this has defaulted to using DB sequences, but because you have not specified any sequence, Hibernate decided to use a single, common sequence, that is shared between all entity definitions.

How to pass data from one html form to multiple tables using spring boot

I have coded three classes (User, UserCredential, Address) where I want to store data into tables using mapping. I am using JSON to store data into tables.
When I store data, data are stored in all tables but in user id it shows 1, in UserCredential id it shows 3 and in Address id it shows 2 while in first entry all id should be 1.
classes are
package com.spring.demo.model;
import java.util.Date;
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.Lob;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String fName;
private String lName;
#Column(unique=true,nullable=true)
private String email;
#Column(unique=true,nullable=true)
private long mobile;
private Date dob;
#Lob
private byte[] image;
#Transient
private String base64Image;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="userCredential_id")
private UserCredential userCredential;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="add_id")
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public UserCredential getUserCredential() {
return userCredential;
}
public void setUserCredential(UserCredential userCredential) {
this.userCreenter code heredential = userCredential;
}
}
UserCredential.java
package com.spring.demo.model;
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.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class UserCredential {
#Id
#Column(name="credential_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(unique=true,nullable=true)
private String username;
private String password;
private String cnfrmpassword;
#JsonIgnore
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="user_id")
private User user;
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 String getCnfrmpassword() {
return cnfrmpassword;
}
public void setCnfrmpassword(String cnfrmpassword) {
this.cnfrmpassword = cnfrmpassword;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Address.java
package com.spring.demo.model;
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;
#Entity
#Table(name="address")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="add_id")
private int id;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="house_no")
private String h_no;
#ManyToOne
#JoinColumn(name="user_id", nullable=true)
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getH_no() {
return h_no;
}
public void setH_no(String h_no) {
this.h_no = h_no;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
i really don't understand how to overcome this problem.
JSON format to store data
{
"fName":"suresh kumst",
"lName":"dingh",
"mobile":4595498366,
"email":"ksuraj1sd00#gmail.com",
"dob":"2012-04-23T18:25:43.511Z",
"address":{
"city":"noida",
"state":"up",
"h_no":"123"
},
"userCredential":{
"username":"ksuraj1asd002",
"password":"12345",
"cnfrmpassword":"12345"
}
}
and the response with different id while they should be 1 in first entry and user id should have value
{
"id": 1,
"fName": "suresh kumst",
"lName": "dingh",
"email": "ksuraj1sd00#gmail.com",
"mobile": 4595498366,
"dob": "2012-04-23T18:25:43.511+0000",
"image": null,
"userCredential": {
"id": 3,
"username": "ksuraj1asd002",
"password": "12345",
"cnfrmpassword": "12345"
},
"address": {
"id": 2,
"city": "noida",
"state": "up",
"h_no": "123",
"user": null
}
}
Here, you are using #GeneratedValue(strategy=GenerationType.AUTO).
Some DB's will use a common sequence to generate and assign the sequence no's. Hibernate will create a table hibernate_sequence and all the entity tables will refer to this table to get the next sequence no. So, the primary keys will be scattered among the entities.
To have the primary key start from 1 for each entity, use #GeneratedValue(strategy=GenerationType.IDENTITY) with each entity.
When you use #GeneratedValue(strategy=GenerationType.AUTO) the underlying ORM framework will use either identity column, sequence or table, depending of the underlying DB. In your case, I guess it is using a sequence (a single sequence for generating IDs for all the tables). If that is the case, in order to achieve that each table IDs are independent from other tables, you'll have to give different sequence name to each entity.
If you're using Hibernate, consider using #GenericGenerator. Example from other SO answer:
#GenericGenerator(
name = "wikiSequenceGenerator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
#Parameter(name = "sequence_name", value = "WIKI_SEQUENCE"),
#Parameter(name = "initial_value", value = "1000"),
#Parameter(name = "increment_size", value = "1")
}
)
#Id
#GeneratedValue(generator = "wikiSequenceGenerator")
Kindly use DB sequence so that you have better control of ID generated, Here I'm just sharing sample of one assuming back end DB is Oracle/mysql
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator = "employee_sequence")
#SequenceGenerator(name = "employee_sequence", sequenceName = "EMP_SN")
private Long empNo;
Here EMP_SN is DB Sequence.
Hope this will solve your problem.

Is it possible to use HQL for Non-Mapped Entities

After Searching stack overflow I came to this
Can I use hibernate query language for entities not mapped to a table?
But recently I was making a small project where the two entities were not mapped by any Mapped Annotations and still I got the result for the query.
So I am confused as the posts say it is not possible to query on Non-Mapped Entities.
Customer
package com.mayank.bitmesra.pojo;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String customerId;
private String name;
private String phoneNumber;
#Temporal(TemporalType.DATE)
private Date dateOfBirth;
#Temporal(TemporalType.DATE)
private Date createdDate;
//for rolling back of Data
//using date as such of now
#Temporal(TemporalType.DATE)
private Date updatedOn;
//for picking up only the data that is most recent
//like a customer can have save with same customer id
//but has different address as his address might have changed up in near future
//will try to handle this in near future
/* #Temporal
private Date lastPickedUpDate;*/
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", phoneNumber=" + phoneNumber + "]";
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#PrePersist
protected void onCreate() {
createdDate = new Date();
}
#PreUpdate
protected void onUpdate() {
updatedOn = new Date();
}
}
OrderDetails
package com.mayank.bitmesra.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class OrderDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String customerId;
private String orderId;
private String orderName;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
}
OrderDetailsDAOImpl
#Repository
#Transactional
public class OrderDetailsDAOImpl implements OrderDetailsDAO{
#PersistenceContext
EntityManager entityManager;
#Override
public List getAllOrderDetails() {
// return entityManager.createQuery("Select order from OrderDetails order ").getResultList();
return entityManager.createQuery("Select customer.name from OrderDetails order inner join Customer customer on order.customerId=customer.customerId").getResultList();
}
I think you are confused . #Entity is the annotation used by HQL to identify the so called mapped entities. Both of the entities are annotated by them.

Categories

Resources