Hi could anyone please help me to resolve this problem,I have an entity called a person, And I have taken the person states(Instance variables) has personname as String type,person petnames as Set type ,personphonnumbers as Set type(Phone is a class type embeddable),And I want to take the personAddress here the Address is a class type (Embeddable),The address stats(Instance variables ) I want to override in my person class by using #AttributeOverride annotation and #Embedded ,But If I override #AttributeOverride annotation and #Embedded my all Set properties(petnames as Set,Set) will not work. If do like this below the person class will ask (create entity Id or create subclass),if I am not using Address property remaining thing is working fine.
PersonEntity
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import org.hibernate.annotations.CollectionOfElements;
/**
*
* #author hyva
*/
#Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#CollectionOfElements
#JoinTable(name = "PET", joinColumns = {
#JoinColumn(name = "person_id")})
#Column(name = "petname")
private Set<String> petname12 = new HashSet<String>();
public Set<PhoneNumber> getPhones() {
return Phones;
}
public void setPhones(Set<PhoneNumber> Phones) {
this.Phones = Phones;
}
#CollectionOfElements
#JoinTable(name = "ponenumbers", joinColumns = {
#JoinColumn(name = "person_id")})
private Set<PhoneNumber> Phones = new HashSet<PhoneNumber>();
#Embedded
private Address homeAddress =new Address();
#AttributeOverrides({
#AttributeOverride(name = "street", column =
#Column(name = "street")),
#AttributeOverride(name = "zip", column =
#Column(name = "zip")),
#AttributeOverride(name = "country", column =
#Column(name = "country"))
})
public Long getId() {
return id;
}
public Set<String> getPetname12() {
return petname12;
}
public void setPetname12(Set<String> petname12) {
this.petname12 = petname12;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean addPets(String p) {
return petname12.add(p);
}
public boolean addPhones(PhoneNumber p) {
return Phones.add(p);
}
#Override
public String toString() {
return "Person{" + "id=" + id + ", name=" + name + ", petname12=" + petname12 + '}';
}
}
Address class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import java.io.Serializable;
import javax.persistence.Embeddable;
/**
*
* #author hyva
*/
#Embeddable
public class Address implements Serializable {
private String street;
private String zip;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
Related
I have an entity Student and an entity Course, and they have many to many relationship, with the Student class being the owner. I'm able to add course for a student but I'm unable to remove a course for a student. I did create a utility method for deleting the connection but it does not work, and I'm not able to find the reason what is wrong. There is no error, it just does nothing.
Maybe anyone encounter anything similar? Thank you in advance
The database schema is a simple many to many relationship
Here is the Student entity:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})//(fetch = FetchType.LAZY)
#JoinTable(name = "student_course",
joinColumns = #JoinColumn(name = "student_id"),
inverseJoinColumns = #JoinColumn(name = "course_id"))
private Set<Course> courseTaken = new HashSet<>();
public Student() {
}
public Student(String firstName, String lastName, Set<Course> courseTaken) {
this.firstName = firstName;
this.lastName = lastName;
this.courseTaken = courseTaken;
}
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 Set<Course> getCourseTaken() {
return courseTaken;
}
public void setCourseTaken(Set<Course> courseTaken) {
this.courseTaken = courseTaken;
}
public void removeCourse(Course tempCourse) {
courseTaken.remove(tempCourse);
tempCourse.getStudentAttending().remove(this);
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", courseTaken="
+ courseTaken + "]";
}
}
Here is a Course entity:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="course")
public class Course implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(name="course_name")
private String courseName;
#Column(name="course_description")
private String courseDescription;
#ManyToMany(mappedBy = "courseTaken")
private Set<Student> studentAttending = new HashSet<>();
public Course() {
}
public Course(String courseName, String courseDescription, Set<Student> studentAttending) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.studentAttending = studentAttending;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public Set<Student> getStudentAttending() {
return studentAttending;
}
public void setStudentAttending(Set<Student> studentAttending) {
this.studentAttending = studentAttending;
}
#Override
public String toString() {
return "Course [id=" + id + ", courseName=" + courseName + ", courseDescription=" + courseDescription + "]";
}
}
Oh, I found what I missed, I just forgot to save the changes into DB, student.save was missing. All works.
#GetMapping("/deleteCourse")
public String deleteCourseForStudent(#RequestParam("courseId") Long courseId, #RequestParam("studentId") Long studentId) {
Course tempCourse = courseService.findById(courseId);
Student tempStudent = studentService.findById(studentId);
tempStudent.removeCourse(tempCourse);
studentService.save(tempStudent);
return "redirect:/student/details?studentId=" + studentId;
}
I have two objects - Role and Privilege. They have a many-to-many relationship. The code of each object is shown below.
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name = "rml_privilege")
public class RmlPrivilege extends RmlBase implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6810028565979325754L;
public static final String ATTR_NAME = "name";
#Column(name="name",nullable=false,unique=true)
private String name;
#Column(name="description")
private String description;
public String getName() {
return name;
}
public void setName(String privilege) {
this.name = privilege;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the RmlRole file.
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "rml_role")
public class RmlRole extends RmlBase {
public final static String ATTR_ORG = "org.id";
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "organization")
private RmlOrganization organization;
//TODO: In case of LAZY loading, recieve an error
#ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinTable(name = "rml_role_privilege", joinColumns = {
#JoinColumn(name = "role", referencedColumnName = "id") }, inverseJoinColumns = {
#JoinColumn(name = "privilege", referencedColumnName = "name") })
Set<RmlPrivilege> privileges;
public RmlOrganization getOrganization() {
return organization;
}
public void setOrganization(RmlOrganization organization) {
this.organization = organization;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<RmlPrivilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Set<RmlPrivilege> privileges) {
this.privileges = privileges;
}
}
When I try to get the RmlRole object, I end up getting the "privileges' variable to be blank. I expect the privilege object set to be prepared. I am doing it wrong somewhere but unable to identify.
My Hibernate version: 5
Java 1.8
Spring Boot application
Any help would be highly appreciated.
I have read so much topics and still I cant solve my problem.
Problem: error from title. I get it every time I try to read entity from database.
Database is mysql one, connected by jdbc driver.
Here is my code: First one is ReadStudentDemo (to read from database)
package entities;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityTransaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class ReadStudentDemo {
public static void main(String[] args) throws ParseException {
Player roggy = new Player();
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
EntityTransaction tx = session.beginTransaction();
roggy = (Player)session.get(Player.class, 4);
tx.commit();
System.out.println(roggy);
}
}
second is Player.java with Player entity mapped.
package entities;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Player generated by hbm2java
*/
#Entity
#Table(name = "Player", catalog = "sql11217012")
public class Player implements java.io.Serializable {
private Integer id;
private String firstName;
private String lastName;
private Date birth;
private Float wl;
private Integer win;
private BigDecimal money;
private Set<Match> matchesForPlayerId = new HashSet<Match>(0);
private Set<Match> matchesForPlayer1Id = new HashSet<Match>(0);
private Set<Match> matchesForCourtId = new HashSet<Match>(0);
public Player() {
}
public Player(String firstName, String lastName, Date birth, Float wl, Integer win, BigDecimal money,
Set<Match> matchesForPlayerId, Set<Match> matchesForPlayer1Id, Set<Match> matchesForCourtId) {
this.firstName = firstName;
this.lastName = lastName;
this.birth = birth;
this.wl = wl;
this.win = win;
this.money = money;
this.matchesForPlayerId = matchesForPlayerId;
this.matchesForPlayer1Id = matchesForPlayer1Id;
this.matchesForCourtId = matchesForCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "first_name", length = 45)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", length = 45)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.DATE)
#Column(name = "birth", length = 10)
public Date getBirth() {
return this.birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
#Column(name = "wl", precision = 12, scale = 0)
public Float getWl() {
return this.wl;
}
public void setWl(Float wl) {
this.wl = wl;
}
#Column(name = "win")
public Integer getWin() {
return this.win;
}
public void setWin(Integer win) {
this.win = win;
}
#Column(name = "money", precision = 15)
public BigDecimal getMoney() {
return this.money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayerId")
public Set<Match> getMatchesForPlayerId() {
return this.matchesForPlayerId;
}
public void setMatchesForPlayerId(Set<Match> matchesForPlayerId) {
this.matchesForPlayerId = matchesForPlayerId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayer1Id")
public Set<Match> getMatchesForPlayer1Id() {
return this.matchesForPlayer1Id;
}
public void setMatchesForPlayer1Id(Set<Match> matchesForPlayer1Id) {
this.matchesForPlayer1Id = matchesForPlayer1Id;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByCourtId")
public Set<Match> getMatchesForCourtId() {
return this.matchesForCourtId;
}
public void setMatchesForCourtId(Set<Match> matchesForCourtId) {
this.matchesForCourtId = matchesForCourtId;
}
}
Then you have Match entity.
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Match", catalog = "sql11217012")
public class Match implements java.io.Serializable {
private Integer id;
private Player playerByPlayerId;
private Player playerByPlayer1Id;
private Player playerByCourtId;
public Match() {
}
public Match(Player playerByPlayerId, Player playerByPlayer1Id, Player playerByCourtId) {
this.playerByPlayerId = playerByPlayerId;
this.playerByPlayer1Id = playerByPlayer1Id;
this.playerByCourtId = playerByCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player_id", nullable = false)
public Player getPlayerByPlayerId() {
return this.playerByPlayerId;
}
public void setPlayerByPlayerId(Player playerByPlayerId) {
this.playerByPlayerId = playerByPlayerId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player1_id", nullable = false)
public Player getPlayerByPlayer1Id() {
return this.playerByPlayer1Id;
}
public void setPlayerByPlayer1Id(Player playerByPlayer1Id) {
this.playerByPlayer1Id = playerByPlayer1Id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "court_id", nullable = false)
public Player getPlayerByCourtId() {
return this.playerByCourtId;
}
public void setPlayerByCourtId(Player playerByCourtId) {
this.playerByCourtId = playerByCourtId;
}
}
And then the stack trace
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Exception in thread "main" org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: entities.Player.matchesForCourtId[entities.Match]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1253)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:810)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:735)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at entities.ReadStudentDemo.main(ReadStudentDemo.java:50)
Thanks in advance for any help!
Well you add Player to your Configuration
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
but seems you never add Match.class?
So probably you should use
Configuration conf = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Player.class)
.addAnnotatedClass(Match.class);
I am generating my Annotated Code Classes with hibernate and eclipse JBoss plugin, For the One to Many & Many to Many Relationships etc, the code generated used Set type for collections and generate many to many as one to many relation.
Project:
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Project generated by hbm2java
*/
#Entity
#Table(name = "project", schema = "public")
public class Project implements java.io.Serializable
{
private int projectId;
private Type type;
private Customer customer;
private String projectName;
private String description;
private Double totalContractAmount;
private Set projectConstructionMaterials = new HashSet( 0 );
public Project()
{
}
public Project(int projectId)
{
this.projectId = projectId;
}
public Project(int projectId, Type type, Customer customer, String projectName, String description,
Double totalContractAmount,
Set projectConstructionMaterials)
{
this.projectId = projectId;
this.type = type;
this.customer = customer;
this.projectName = projectName;
this.description = description;
this.totalContractAmount = totalContractAmount;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "project_id", unique = true, nullable = false)
public int getProjectId()
{
return this.projectId;
}
public void setProjectId(int projectId)
{
this.projectId = projectId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "customer_id")
public Customer getCustomer()
{
return this.customer;
}
public void setCustomer(Customer customer)
{
this.customer = customer;
}
#Column(name = "project_name")
public String getProjectName()
{
return this.projectName;
}
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "project") //it should be many to many annotation
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
ProjectConstructionMaterial
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* ProjectConstructionMaterial generated by hbm2java
*/
#Entity
#Table(name = "project_construction_material", schema = "public")
public class ProjectConstructionMaterial implements java.io.Serializable
{
private int projectConstructionMaterialId;
private ConstructionMaterialInventory constructionMaterialInventory;
private Project project;
private String description;
private String quantityArrived;
private String quantityConsumed;
public ProjectConstructionMaterial()
{
}
public ProjectConstructionMaterial(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
public ProjectConstructionMaterial(int projectConstructionMaterialId,
ConstructionMaterialInventory constructionMaterialInventory, Project project, String description,
String quantityArrived, String quantityConsumed)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
this.constructionMaterialInventory = constructionMaterialInventory;
this.project = project;
this.description = description;
this.quantityArrived = quantityArrived;
this.quantityConsumed = quantityConsumed;
}
#Id
#Column(name = "project_construction_material_id", unique = true, nullable = false)
public int getProjectConstructionMaterialId()
{
return this.projectConstructionMaterialId;
}
public void setProjectConstructionMaterialId(int projectConstructionMaterialId)
{
this.projectConstructionMaterialId = projectConstructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "construction_material_id")
public ConstructionMaterialInventory getConstructionMaterialInventory()
{
return this.constructionMaterialInventory;
}
public void setConstructionMaterialInventory(ConstructionMaterialInventory constructionMaterialInventory)
{
this.constructionMaterialInventory = constructionMaterialInventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "project_id")
public Project getProject()
{
return this.project;
}
public void setProject(Project project)
{
this.project = project;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#Column(name = "quantity_arrived")
public String getQuantityArrived()
{
return this.quantityArrived;
}
public void setQuantityArrived(String quantityArrived)
{
this.quantityArrived = quantityArrived;
}
#Column(name = "quantity_consumed")
public String getQuantityConsumed()
{
return this.quantityConsumed;
}
public void setQuantityConsumed(String quantityConsumed)
{
this.quantityConsumed = quantityConsumed;
}
}
ConstructionMaterialInventory
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* ConstructionMaterialInventory generated by hbm2java
*/
#Entity
#Table(name = "construction_material_inventory", schema = "public")
public class ConstructionMaterialInventory implements java.io.Serializable
{
private int constructionMaterialId;
private Type type;
private SubType subType;
private String quantity;
private String description;
private Set projectConstructionMaterials = new HashSet( 0 );
public ConstructionMaterialInventory()
{
}
public ConstructionMaterialInventory(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
public ConstructionMaterialInventory(int constructionMaterialId, Type type, SubType subType, String quantity,
String description, Set projectConstructionMaterials)
{
this.constructionMaterialId = constructionMaterialId;
this.type = type;
this.subType = subType;
this.quantity = quantity;
this.description = description;
this.projectConstructionMaterials = projectConstructionMaterials;
}
#Id
#Column(name = "construction_material_id", unique = true, nullable = false)
public int getConstructionMaterialId()
{
return this.constructionMaterialId;
}
public void setConstructionMaterialId(int constructionMaterialId)
{
this.constructionMaterialId = constructionMaterialId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type_id")
public Type getType()
{
return this.type;
}
public void setType(Type type)
{
this.type = type;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sub_type_id")
public SubType getSubType()
{
return this.subType;
}
public void setSubType(SubType subType)
{
this.subType = subType;
}
#Column(name = "quantity")
public String getQuantity()
{
return this.quantity;
}
public void setQuantity(String quantity)
{
this.quantity = quantity;
}
#Column(name = "description", length = 500)
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "constructionMaterialInventory")
public Set getProjectConstructionMaterials()
{
return this.projectConstructionMaterials;
}
public void setProjectConstructionMaterials(Set projectConstructionMaterials)
{
this.projectConstructionMaterials = projectConstructionMaterials;
}
}
Data Model
I want to change it to many to many annotations and also want to use List or ArrayList instead of Set. Can anyone please tell me how to do this with automatically code generation? Beause i have dozens of table like this and change in tables manually takes too much time..
For Example: Annotation Must be generate automatically as described in this example.
Many to Many annotation Example
As I referenced in the title I have two entities in google app engine project. The first one is "store" and the other is "product". Before adding the ManyToMany annotation the entities stored regularly but after the relationship addition the entities cannot be stored even though there is a successful message returned!!
Here are the entities:
Store.java
package com.cheapchase.server;
import java.util.Date;
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;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="store", catalog="content", uniqueConstraints={
#UniqueConstraint(columnNames = "STORE_NAME"),
#UniqueConstraint(columnNames = "STORE_CODE")})
public class Store{
private int storeCode;
private Date dueDate;
private String emailAddress;
private String storeName;
private String storeAddress;
private String storeDescription;
private String userId;
private Long id;
private Set<Product> product;
public Store(){
}
public Store(String storeName, int storeCode){
this.storeName = storeName;
this.setStoreCode(storeCode);
}
public Store(String storeName, int storeCode, Set<Product> product){
this.storeName = storeName;
this.storeCode = storeCode;
this.product = product;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "STORE_ID", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="STORE_NAME", nullable=false)
public String getStoreName() {
return this.storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
/*
* Define the Many To Many relationship with product
*/
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "storae_product", catalog = "content", joinColumns = {
#JoinColumn(name = "STORE_ID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "PRODUCT_ID", nullable = false)})
public Set<Product> getProduct(){
return this.product;
}
public void setProduct(Set<Product> product){
this.product = product;
}
/*
* Define the rest getters and setters
*/
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String storeDescription) {
this.storeDescription = storeDescription;
}
public String getStoreAddress() {
return storeAddress;
}
public void setStoreAddress(String storeAddress) {
this.storeAddress = storeAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getStoreCode() {
return storeCode;
}
public void setStoreCode(int storeCode) {
this.storeCode = storeCode;
}
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("Store [dueDate=");
builder.append(dueDate);
builder.append(", name=");
builder.append(storeName);
builder.append(", description=");
builder.append(storeDescription);
builder.append("]");
return builder.toString();
}
}
Product.java
package com.cheapchase.server;
import java.util.Set;
import java.util.HashSet;
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;
import javax.persistence.Column;
import com.google.appengine.api.datastore.Blob;
#Entity
#Table(name = "product", catalog = "content")
public class Product {
private Long productId;
private String name;
private String description;
private int barCode;
Blob image;
private Set<Store> stores = new HashSet<Store>(0);
public Product(){
}
public Product(String name, String description){
this.name = name;
this.description = description;
}
public Product(String name, String description, Set<Store> stores){
this.name = name;
this.description = description;
this.stores = stores;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
public Long getProductId(){
return this.productId;
}
public void setProductId(Long productId){
this.productId = productId;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "product")
public Set<Store> getStore(){
return this.stores;
}
public void setStore(Set<Store> store){
this.stores = store;
}
public int getBarCode() {
return barCode;
}
public void setBarCode(int barCode) {
this.barCode = barCode;
}
}