I'm trying to create One-To-Many relationship between two objects but I got this error. I don't know how to mapping property ID from object MyUserAccount to object Book. ID is a String data received from Google (I'm doing Social Login in my project).
Error
PreparedStatementCallback; SQL [INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) VALUES ( ?, ?, ?, ?, ?, ?, ?)]; Field 'ID' doesn't have a default value; nested exception is java.sql.SQLException: Field 'ID' doesn't have a default value
BookDao (How I save object Book into database)
public void save(Book book) {
// TODO Auto-generated method stub
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) "
+ "VALUES ( :tensach, :tacgia, :nhanxet, :tinhtrang, :theloai, :image, :image_name)";
namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(book), keyHolder);
book.setBook_ID(keyHolder.getKey().intValue());
}
private SqlParameterSource getSqlParameterByModel(Book book) {
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("book_id", book.getBook_ID());
paramSource.addValue("tensach", book.getTensach());
paramSource.addValue("tacgia", book.getTacgia());
paramSource.addValue("nhanxet", book.getNhanxet());
paramSource.addValue("tinhtrang", book.getTinhtrang());
paramSource.addValue("image", book.getImage());
paramSource.addValue("image_name", book.getImage_name());
paramSource.addValue("theloai", book.getTheloai());
return paramSource;
}
Model Book
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private Integer book_ID;
private String tensach;
private String tacgia;
private String nhanxet;
private String tinhtrang;
private String theloai;
private byte[] image;
private String image_name;
private String data;
private MyUserAccount myUserAccount;
public Book() {
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = false)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
public void setMyUserAccount(MyUserAccount myUserAccount) {
this.myUserAccount = myUserAccount;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "book_id", unique = true, nullable = false)
public Integer getBook_ID() {
return book_ID;
}
#Column(name = "image_name")
public String getImage_name() {
return image_name;
}
#Column(name = "tensach", length = 50, nullable = true)
public String getTensach() {
return tensach;
}
#Lob
#Type(type = "org.hibernate.type.BinaryType")
#Column(name = "image", columnDefinition = "LONGBLOB", nullable = true)
public byte[] getImage() {
return image;
}
#Column(name = "tacgia", length = 50, nullable = true)
public String getTacgia() {
return tacgia;
}
#Column(name = "nhanxet", length = 100, nullable = true)
public String getNhanxet() {
return nhanxet;
}
#Column(name = "tinhtrang", length = 50, nullable = true)
public String getTinhtrang() {
return tinhtrang;
}
#Column(name = "theloai", length = 50, nullable = true)
public String getTheloai() {
return theloai;
}
#Column(name = "data", length = 16777215)
public String getData() {
return data;
}
public void setBook_ID(Integer book_ID) {
this.book_ID = book_ID;
}
public void setImage_name(String image_name) {
this.image_name = image_name;
}
public void setImage(byte[] image) {
this.image = image;
}
public void setTensach(String tensach) {
this.tensach = tensach;
}
public void setTacgia(String tacgia) {
this.tacgia = tacgia;
}
public void setNhanxet(String nhanxet) {
this.nhanxet = nhanxet;
}
public void setTinhtrang(String tinhtrang) {
this.tinhtrang = tinhtrang;
}
public void setTheloai(String theloai) {
this.theloai = theloai;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return "Book [book_ID=" + book_ID + ", tensach=" + tensach + ", tacgia=" + tacgia + ", nhanxet=" + nhanxet
+ ", tinhtrang=" + tinhtrang + ", theloai=" + theloai + ", image=" + Arrays.toString(image) + "]";
}
}
Model MyUserAccount.
public class MyUserAccount implements Serializable {
private static final long serialVersionUID = 1L;
public static final String ROLE_USER = "ROLE_USER";
private String id;
private String email;
private String userName;
private String firstName;
private String lastName;
private String password;
private String role;
private String enabled;
private List<Book> book = new ArrayList<Book>(0);
public MyUserAccount() {
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "myUserAccount")
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
public MyUserAccount(String id, String email, String userName, String firstName, //
String lastName, String password, String role, String enabled) {
this.id = id;
this.email = email;
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.role = role;
this.enabled = enabled;
}
#Id
#Column(name = "ID", unique = true, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name = "EMAIL", unique = true, nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "USER_NAME", unique = true, nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "FIRST_NAME", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "ROLE", nullable = false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Column(name = "ENABLED", columnDefinition = "VARCHAR(1) default 'Y'", nullable = false)
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
}
Controller
#RequestMapping(value = "/motsach/add/", method = RequestMethod.POST)
public String saveBook(#ModelAttribute("bookForm") #Validated Book book, BindingResult result, Model model,
#RequestParam CommonsMultipartFile[] image, String userName, final RedirectAttributes redirectAttributes)
throws IOException, UnsupportedEncodingException {
MyUserAccount myUserAccount = myUserAccountDAO.findByUserName(userName);
System.out.println(userName + "sssssssssssss");
book.setMyUserAccount(myUserAccount);
redirectAttributes.addFlashAttribute("css", "success");
if (book.getBook_ID() == null) {
System.out.println(book.getBook_ID());
redirectAttributes.addFlashAttribute("msg", "book added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "book updated successfully!");
}
for (CommonsMultipartFile aFile : image) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
book.setImage_name(aFile.getOriginalFilename());
book.setImage(aFile.getBytes());
System.out.println("Damn that Shit!");
}
bookService.saveOrUpdate(book);
// POST/REDIRECT/GET
return "redirect:/motsach/" + book.getBook_ID();
}
You have a #manyToOne (with ID as name ) relation that can't be null. So in order to add a book you have to set MyUserAccount to a book before saving or you can turn into :
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = true)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
and modify your column in your database to set the possibility of null value.
Related
I'm trying to save an object in my MySQL DB by using Spring JPA.
That's the error I get:
[nio-8088-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved
[org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction]
That's where I'm trying to save my object:
#Override
public RegistrationV1Response registerUser(#Valid RegistrationV1Request registrationV1Request) {
User user = new User();
user.setFirstname(registrationV1Request.getFirstname());
user.setLastname(registrationV1Request.getLastname());
user.setUsername(registrationV1Request.getUsername());
user.setEmail(registrationV1Request.getEmail());
user.setPassword(new BCryptPasswordEncoder().encode(registrationV1Request.getPassword()));
user.setActive(true);
userRepository.save(user);
return new RegistrationV1Response().withUser(user);
}
The UserRepository:
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
public User findFirstByUsername(String username);
}
The User class:
#javax.persistence.Entity
#Table(name = "users")
public class User extends Entity {
#Column(name = "firstname", nullable = false, length = 100)
#NotEmpty()
private String firstname;
#Column(name = "lastname", nullable = false, length = 100)
#NotEmpty()
private String lastname;
#Column(name = "password", nullable = false, length = 100)
#NotEmpty()
private String password;
#Column(name = "username", nullable = false, unique = true, length = 100)
#NotEmpty()
private String username;
#Column(name = "email", nullable = false, unique = true, length = 100)
#NotEmpty()
#Email()
private String email;
#Column(name = "active", nullable = false)
#NotEmpty()
private boolean active;
#Column(name = "description", nullable = true, length = 250)
private String description;
#OneToMany(targetEntity = Post.class, mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Post> posts;
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 getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Post> getPosts() { return posts; }
public void setPosts(List<Post> posts) { this.posts = posts; }
}
The Post class:
#javax.persistence.Entity
#Table(name = "posts")
public class Post extends Entity {
#Lob
#Column(name = "text", nullable = false)
#NotEmpty()
private String text;
#ManyToOne(targetEntity = User.class)
private User user;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Reading from the DB work's without any problems just save (insert / update) doesn't work.
I just read on a similar issue that I need to add the #Transational property to the method. I did this and it's still not working. Also the other possible solutions / statements of similar issues aren't working. They're mostly about missconfigured relations or something and that's not the problem in my case I think.
I'm starting from scratch a new project and i got this problem which i cannot solve. I have three entities, and they all have a manytomany relationship with each other. There is the Cluster:
#Entity
#Component
#Table(name = "clusterEntity")
public class Cluster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToMany
#JoinTable(name="cluster_user",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_cluster;
#ManyToMany
#JoinTable(name="cluster_sito",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"))
private List<Sito> sitos;
#Override
public String toString() {
return "Cluster{" +
"id=" + id +
", name='" + name +
", users='" + users_cluster.toString() +
'}';
}
}
This is the User:
#Entity
#Component
#Table(name = "userEntity")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password_hash", nullable = false)
private String passwordHash;
#Column(name = "role", nullable = false)
#Enumerated(EnumType.STRING)
private Role role;
#Column(name = "G1", nullable = true)
private String G1;
#Column(name = "G2", nullable = true)
private String G2;
#Column(name = "G3", nullable = true)
private String G3;
#Column(name = "G4", nullable = true)
private String G4;
#Column(name = "G5", nullable = true)
private String G5;
#Column(name = "G6", nullable = true)
private String G6;
#Column (name = "access_token", nullable = true)
private String access_token;
#Column (name = "refresh_token", nullable = true)
private String refresh_token;
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getG1() {
return G1;
}
public void setG1(String g1) {
G1 = g1;
}
public String getG2() {
return G2;
}
public void setG2(String g2) {
G2 = g2;
}
public String getG3() {
return G3;
}
public void setG3(String g3) {
G3 = g3;
}
public String getG4() {
return G4;
}
public void setG4(String g4) {
G4 = g4;
}
public String getG5() {
return G5;
}
public void setG5(String g5) {
G5 = g5;
}
public String getG6() {
return G6;
}
public void setG6(String g6) {
G6 = g6;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
#ManyToMany(mappedBy="users_cluster")
private List<User> users_cluster;
#ManyToMany(mappedBy="users_sito")
private List<User> users_sito;
public User(){}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email.replaceFirst("#.*", "#***") +
", passwordHash='" + passwordHash.substring(0, 10) +
", role=" + role +
'}';
}
}
This is the Sito:
#Entity
#Component
#Table(name = "sitoEntity")
public class Sito {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_sito;
#Override
public String toString() {
return "Sito{" +
"id=" + id +
", name='" + name+
", users='" + users_sito.toString()+
'}';
}
}
When i try compiling with maven i get the following error about mappedBY, as if it was written on both side of the relation, but in fact it is written only on one side:
Caused by: org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: User.users_cluster
Anyone has any ideaof what am i doing wrong?
Clustor
As far as I can see the Cluster entity is annotated correctly except some kine of naming convention. Instead of
private List<User> users_cluster;
I would recommend using
private List<User> users;
The list contains users so it should be named to reflect that; good naming is the best documentation, (imo).
User
This entity seems to be correctly annotated but the references are wrong as they are self referencing. So the entity should be modified as follows if you want to create a many-to-many relationship between the thre entities:
public class User {
// ...
#ManyToMany(mappedBy="users")
private List<Cluster> clusters;
#ManyToMany(mappedBy="users")
private List<Sito> sitos;
// getters + setters
}
Sito
Here too I made a small modification as follows:
public class Sito {
// ...
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users;
#ManyToMany(mappedBy = "sitos")
private List<Cluster> clusters;
// getters + setters
}
Now your three entities should be related to each other as you desired.
I need to save the child table values without retrieve the values.
POJO Class:
public class User {
private String firstName;
#Id
#SequenceGenerator(name = "userID", sequenceName = "userID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
#Column(name = "id")
private Long id;
private String lastName;
private Integer passwordReset;
#Column(name = "useremail", nullable = false, unique = true)
#Email
#NotEmpty
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<WashingOrder> orderList;
#Column(unique = true)
#NotEmpty(message = "{username}")
private String username;
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setId(Long id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPasswordReset() {
return passwordReset;
}
public void setPasswordReset(Integer passwordReset) {
this.passwordReset = passwordReset;
}
public List<WashingOrder> getOrderList() {
return orderList;
}
public void setOrderList(List<WashingOrder> orderList) {
this.orderList = orderList;
}
}
public class WashingOrder {
#Id
#SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
#Column(name = "orderNo")
private Long orderNo;
#Column(name = "totalClothes", nullable = false)
#NotNull
private Integer totalClothes;
#Column(name = "mensCloth", nullable = true)
private Integer mensCloth;
#Column(name = "womensCloth", nullable = true)
private Integer womensCloth;
#Column(name = "otherCloth", nullable = true)
private Integer otherClothes;
#Column(name = "deliveryDate", nullable = true)
/* #DateTimeFormat(pattern = "yyyy-mm-dd") */
private Date deliveryDate;
#Column(name = "status", nullable = true)
private String orderStatus;
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getTotalClothes() {
return totalClothes;
}
public void setTotalClothes(Integer totalClothes) {
this.totalClothes = totalClothes;
}
public Integer getMensCloth() {
return mensCloth;
}
public void setMensCloth(Integer mensCloth) {
this.mensCloth = mensCloth;
}
public Integer getWomensCloth() {
return womensCloth;
}
public void setWomensCloth(Integer womensCloth) {
this.womensCloth = womensCloth;
}
public Integer getOtherClothes() {
return otherClothes;
}
public void setOtherClothes(Integer otherClothes) {
this.otherClothes = otherClothes;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
Implementation:
Session session = sessionFactory.getCurrentSession();
long id = 1;
Query query = session.createQuery("from user where id =" + id);
User emp6 = (User) session.load(User.class, new Long(1));
User user = (User) query.uniqueResult();
List<WashingOrder> washingOrder = user.getOrderList();
washingOrder.add(order);
user.setOrderList(washingOrder);
session.save(user);
Long orderID = (long) 1;
return orderID;
Here if you check I am getting the order list first (user.getOrderList()) and then I am adding the new list and saving the user.
But I want to save the new order list of the user without retrieve the previous order list.
There is any possibility for the adding new order data without retrieve the previous order list of the particular user.
You need to change a mapping
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<WashingOrder> orderList;
}
public class WashingOrder {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, 1L);
WashingOrder order = new WashingOrder();
order.setUser(user);
session.save(order);
You can try to use a fake User instead of loading
WashingOrder order = new WashingOrder();
order.setUser(new User(1L));
session.save(order);
I searched lot. But can't find solution for my case. i want create hibernate criteria for following query.
SELECT * FROM patient as p1 LEFT OUTER JOIN (SELECT * FROM patient_caller_admin_map WHERE caller_admin_id='1') as pca ON p1.patient_id=pca.patient_id;
i went through the DetachedCriteria , Criteria and created the following things. But don't know how to use LEFT_JOIN by joining both.
DetachedCriteria inner=DetachedCriteria.forClass(PatientCallerAdminMap.class, "patientCallerAdmin");
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
PatientCallerAdminMap Entity:
/**
* PatientCallerAdminMap generated by hbm2java
*/
#Entity
#Table(name = "patient_caller_admin_map", catalog = "test")
public class PatientCallerAdminMap implements java.io.Serializable {
private PatientCallerAdminMapId id;
private CallerAdmin callerAdmin;
private Caller caller;
private Patient patient;
private String notes;
private Integer isArchived;
private Integer patientStatus;
private Set<CallLog> callLogs = new HashSet<CallLog>(0);
private Set<CallLog> callLogs_1 = new HashSet<CallLog>(0);
public PatientCallerAdminMap() {
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Patient patient) {
this.id = id;
this.callerAdmin = callerAdmin;
this.patient = patient;
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Caller caller, Patient patient,
String notes, Integer isArchived, Integer patientStatus,
Set<CallLog> callLogs, Set<CallLog> callLogs_1) {
this.id = id;
this.callerAdmin = callerAdmin;
this.caller = caller;
this.patient = patient;
this.notes = notes;
this.isArchived = isArchived;
this.patientStatus = patientStatus;
this.callLogs = callLogs;
this.callLogs_1 = callLogs_1;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "patientId", column = #Column(name = "patient_id", nullable = false)),
#AttributeOverride(name = "callerAdminId", column = #Column(name = "caller_admin_id", nullable = false)) })
public PatientCallerAdminMapId getId() {
return this.id;
}
public void setId(PatientCallerAdminMapId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_admin_id", nullable = false, insertable = false, updatable = false)
public CallerAdmin getCallerAdmin() {
return this.callerAdmin;
}
public void setCallerAdmin(CallerAdmin callerAdmin) {
this.callerAdmin = callerAdmin;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_id")
public Caller getCaller() {
return this.caller;
}
public void setCaller(Caller caller) {
this.caller = caller;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, insertable = false, updatable = false)
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
#Column(name = "notes", length = 600)
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Column(name = "is_archived")
public Integer getIsArchived() {
return this.isArchived;
}
public void setIsArchived(Integer isArchived) {
this.isArchived = isArchived;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs() {
return this.callLogs;
}
public void setCallLogs(Set<CallLog> callLogs) {
this.callLogs = callLogs;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs_1() {
return this.callLogs_1;
}
public void setCallLogs_1(Set<CallLog> callLogs_1) {
this.callLogs_1 = callLogs_1;
}
}
Patient Entity Class:
#Entity
#Table(name = "patient", catalog = "test")
public class Patient implements java.io.Serializable {
private String patientId;
private String addedDate;
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String phoneNumber;
private Integer tier;
private Integer patientStatus;
private Integer status;
private Set<PatientCallerAdminMap> patientCallerAdminMaps = new HashSet<PatientCallerAdminMap>(
0);
public Patient() {
}
public Patient(String patientId) {
this.patientId = patientId;
}
public Patient(String patientId,String addedDate, String timeOfCrash,
String name, String dateOfBirth, String gender,
String address,
String phoneNumber,Integer tier, Integer patientStatus,
Integer status,
Set<PatientCallerAdminMap> patientCallerAdminMaps,
) {
this.patientId = patientId;
this.addedDate = addedDate;
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.phoneNumber = phoneNumber;
this.tier=tier;
this.patientStatus = patientStatus;
this.status = status;
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
#Id
#Column(name = "patient_id", unique = true, nullable = false)
public String getPatientId() {
return this.patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
#Column(name = "added_date", length = 45)
public String getAddedDate() {
return addedDate;
}
public void setAddedDate(String addedDate) {
this.addedDate = addedDate;
}
#Column(name = "name", length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "date_of_birth", length = 45)
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "gender", length = 5)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name = "address", length = 200)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "phone_number", length = 20)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "tier")
public Integer getTier() {
return this.tier;
}
public void setTier(Integer tier) {
this.tier = tier;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
public Set<PatientCallerAdminMap> getPatientCallerAdminMaps() {
return this.patientCallerAdminMaps;
}
public void setPatientCallerAdminMaps(
Set<PatientCallerAdminMap> patientCallerAdminMaps) {
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
}
Please help to solve this.
Maybe you can achieve this without using subquery so the query become simpler :
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
cr2=cr1.createCriteria("patientCallerAdminMaps ",CriteriaSpecification.LEFT_JOIN);
cr3= cr2.createCriteria("callerAdmin",CriteriaSpecification.LEFT_JOIN);
cr3.add(Restrictions.eq("id", "1"));
For the "select *" you can't do it with criteria. This criteria will return a list of Patient entity.
If really want * you will have to add alias on subcriteria and use Projection to select explicitly the fields that you want
I have a doubt and consequently I don't know how proceed correctly. I have three different tables like in figure below. I'm using JPA. Here is the code generated automatically by Netbeans that shows the entities. My question is What should I persist into the database? If I put only user, I will have automatically persisted also phone numbers and client? i'm pretty confused
Here it is a code
UserCredential user = new UserCredential();
user.setUsername(username);
user.setPassword(utilBean.hashPassword(password));
user.setEmail(email);
Client client = new Client();
client.setUserCredential(user);
client.setName(name);
client.setSurname(surname);
client.setAddress(address);
client.setCity(city);
client.setZipCode(zipCode);
client.setCountry(country);
client.setFidelityPoints(0);
ClientPhoneNumbers phoneNumber = new ClientPhoneNumbers();
phoneNumber.setUsername(username);
if(homeNumber != null || !(homeNumber.equals("")))
{
phoneNumber.setCountryCodeHome(areaCodeHomeNumber);
phoneNumber.setHome(homeNumber);
}
phoneNumber.setCountryCodeMobile(areaCodeMobileNumber);
phoneNumber.setMobile(mobileNumber);
client.setClientPhoneNumbers(phoneNumber);
em.persist(user);
USER CREDENTIAL
#Entity
#Table(name = "user_credential")
#NamedQueries(
{
#NamedQuery(name = "UserCredential.findAll", query = "SELECT u FROM UserCredential u")
})
public class UserCredential implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "email")
private String email;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "password")
private String password;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "groupname")
private String groupname;
#Column(name = "create_time")
#Temporal(TemporalType.TIMESTAMP)
private Date createTime;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "userCredential")
private Client client;
public UserCredential()
{
}
public UserCredential(String username)
{
this.username = username;
}
public UserCredential(String username, String email, String password, String groupname)
{
this.username = username;
this.email = email;
this.password = password;
this.groupname = groupname;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getGroupname()
{
return groupname;
}
public void setGroupname(String groupname)
{
this.groupname = groupname;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UserCredential))
{
return false;
}
UserCredential other = (UserCredential) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.UserCredential[ username=" + username + " ]";
}
}
CLIENT
#Entity
#Table(name = "client")
#NamedQueries(
{
#NamedQuery(name = "Client.findAll", query = "SELECT c FROM Client c")
})
public class Client implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "surname")
private String surname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "address")
private String address;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "city")
private String city;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "zip_code")
private String zipCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "country")
private String country;
#Basic(optional = false)
#NotNull
#Column(name = "fidelity_points")
private int fidelityPoints;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "client")
private ClientPhoneNumbers clientPhoneNumbers;
#JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
#OneToOne(optional = false)
private UserCredential userCredential;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "username")
private Collection<Reservation> reservationCollection;
public Client()
{
}
public Client(String username)
{
this.username = username;
}
public Client(String username, String name, String surname, String address, String city, String zipCode, String country, int fidelityPoints)
{
this.username = username;
this.name = name;
this.surname = surname;
this.address = address;
this.city = city;
this.zipCode = zipCode;
this.country = country;
this.fidelityPoints = fidelityPoints;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getZipCode()
{
return zipCode;
}
public void setZipCode(String zipCode)
{
this.zipCode = zipCode;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public int getFidelityPoints()
{
return fidelityPoints;
}
public void setFidelityPoints(int fidelityPoints)
{
this.fidelityPoints = fidelityPoints;
}
public ClientPhoneNumbers getClientPhoneNumbers()
{
return clientPhoneNumbers;
}
public void setClientPhoneNumbers(ClientPhoneNumbers clientPhoneNumbers)
{
this.clientPhoneNumbers = clientPhoneNumbers;
}
public UserCredential getUserCredential()
{
return userCredential;
}
public void setUserCredential(UserCredential userCredential)
{
this.userCredential = userCredential;
}
public Collection<Reservation> getReservationCollection()
{
return reservationCollection;
}
public void setReservationCollection(Collection<Reservation> reservationCollection)
{
this.reservationCollection = reservationCollection;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Client))
{
return false;
}
Client other = (Client) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.Client[ username=" + username + " ]";
}
}
** PHONE NUMBERS **
#Entity
#Table(name = "client_phone_numbers")
#NamedQueries(
{
#NamedQuery(name = "ClientPhoneNumbers.findAll", query = "SELECT c FROM ClientPhoneNumbers c")
})
public class ClientPhoneNumbers implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
#Size(max = 8)
#Column(name = "country_code_home")
private String countryCodeHome;
#Size(max = 45)
#Column(name = "home")
private String home;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 8)
#Column(name = "country_code_mobile")
private String countryCodeMobile;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "mobile")
private String mobile;
#JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
#OneToOne(optional = false)
private Client client;
public ClientPhoneNumbers()
{
}
public ClientPhoneNumbers(String username)
{
this.username = username;
}
public ClientPhoneNumbers(String username, String countryCodeMobile, String mobile)
{
this.username = username;
this.countryCodeMobile = countryCodeMobile;
this.mobile = mobile;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getCountryCodeHome()
{
return countryCodeHome;
}
public void setCountryCodeHome(String countryCodeHome)
{
this.countryCodeHome = countryCodeHome;
}
public String getHome()
{
return home;
}
public void setHome(String home)
{
this.home = home;
}
public String getCountryCodeMobile()
{
return countryCodeMobile;
}
public void setCountryCodeMobile(String countryCodeMobile)
{
this.countryCodeMobile = countryCodeMobile;
}
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ClientPhoneNumbers))
{
return false;
}
ClientPhoneNumbers other = (ClientPhoneNumbers) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.ClientPhoneNumbers[ username=" + username + " ]";
}
}
If you want to persist client as well, you have to call user.setClient(client) before calling persist.