Hibernate Annotations Perform Inner Join - java

Hello I have just started learning hibernate. Please correct me where I am doing mistake. I want do a one-to-many relationship between two tables using a join table using hibernate annotations.
create table assembly
(
assembly_id serial primary key,
number text,
user_id int
);
create table assembly_properties
(
property_id serial primary key,
property_name text,
property_type text
);
create table assembly_properties_mapping
(
mapping_id serial primary key,
assembly_id int,
property_id int,
property_value text,
CONSTRAINT FK_assembly_id FOREIGN KEY (assembly_id) REFERENCES assembly(assembly_id),
CONSTRAINT FK_property_id FOREIGN KEY (property_id) REFERENCES assembly_properties(property_id)
);
I have created these three table in postgres sql database. Below is my Assembly.class
package com.development.wrapper;
#Entity
#Table(name = "assembly")
public class Assembly {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "assembly_id")
private int assembly_id;
#Column(name = "number")
private String number;
#Column(name ="UserID")
private int userId;
#Column
#ElementCollection(targetClass = AssemblyProperties.class)
private Set<AssemblyProperties> assembly_properties;
public int getAssembly_id() {
return assembly_id;
}
public void setAssembly_id(int assembly_id) {
this.assembly_id = assembly_id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#OneToMany(targetEntity = AssemblyProperties.class, cascade = CascadeType.ALL)
#JoinTable(name = "assembly_properties_mapping", joinColumns = { #JoinColumn(name = "assembly_id") }, inverseJoinColumns = { #JoinColumn(name = "property_id") })
public Set<AssemblyProperties> getAssembly_properties() {
return assembly_properties;
}
public void setAssembly_properties(Set<AssemblyProperties> assembly_properties) {
this.assembly_properties = assembly_properties;
}
}
Below is AssemblyProperties.class
package com.development.wrapper;
#Entity
#Table(name = "assembly_properties")
public class AssemblyProperties {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "property_id")
private int property_id;
#Column(name = "property_name")
private String property_name;
#Column(name = "property_type")
private String property_type;
public int getProperty_id() {
return property_id;
}
public void setProperty_id(int property_id) {
this.property_id = property_id;
}
public String getProperty_name() {
return property_name;
}
public void setProperty_name(String property_name) {
this.property_name = property_name;
}
public String getProperty_type() {
return property_type;
}
public void setProperty_type(String property_type) {
this.property_type = property_type;
}
}
When I am trying to load data in database table as given below I am getting an error Failed to create sessionFactory object.org.hibernate.MappingException: Could not determine type for: com.development.wrapper.AssemblyProperties, at table: Assembly_assembly_properties, for columns: [org.hibernate.mapping.Column(assembly_properties)]
Exception in thread "main" java.lang.ExceptionInInitializerError
below is code I am trying to run
public class Test
{
SessionFactory factory;
public Test() throws Exception
{
try
{
factory = new AnnotationConfiguration().configure().
addPackage("com.development.wrapper"). //add package if used.
addAnnotatedClass(Assembly.class).buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public Integer addClass(Assembly assembly)
{
Session session = factory.openSession();
Transaction tx = null;
Integer assemblyid = null;
try
{
tx = session.beginTransaction();
assemblyid = (Integer) session.save(assembly);
System.out.println(assemblyid);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return assemblyid;
}
public static void main(String[] args) throws Exception {
Set<AssemblyProperties> assemblyProperties = new HashSet<AssemblyProperties>();
AssemblyProperties ass=new AssemblyProperties();
ass.setProperty_name("xx");
ass.setProperty_type("List");
assemblyProperties.add(ass);
Assembly assembly =new Assembly();
assembly.setAssembly_properties(assemblyProperties);
assembly.setNumber("aaa");
assembly.setUserId(1);
Test test=new Test();
test.addClass(assembly);
}
}
Please help me to resolve this error/ Thanks in advance.

Hibernate can't handle when the annotations for public setters and private fields are mixed in one class.
A possible solution would be to make all of your annotations at the public setters instead of mixing it between the private fields and the public setters, that way you can avoid the case where there are annotations both at public and private access modifiers.

Your annotations are conflicting. this:
#Column
#ElementCollection(targetClass = AssemblyProperties.class)
private Set<AssemblyProperties> assembly_properties;
and this:
#OneToMany(targetEntity = AssemblyProperties.class, cascade = CascadeType.ALL)
#JoinTable(name = "assembly_properties_mapping", joinColumns = { #JoinColumn(name = "assembly_id") }, inverseJoinColumns = { #JoinColumn(name = "property_id") })
public Set<AssemblyProperties> getAssembly_properties() {
return assembly_properties;
}
just remove first annotaions over private field (assembly_properties).

Related

How to POST ArrayList to spring boot H2 DB

Im getting the following error:
{"timestamp":1535929757444,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.DataIntegrityViolationException","message":"could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.WT_TASK(TASK_ID)\"; SQL statement:\ninsert into wt_task (exercise_id, task_id) values (?, ?) [23505-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement","path":"/api/word-transformation/new"}
I was able to create a service to fetch JSON from the database but I cant manage to upload them.
This is my service:
public WordTransformationExercise save(WordTransformationExerciseRequest wtRequest) {
WordTransformationExercise wordTransformation = new WordTransformationExercise();
wordTransformation.setAuthorId(wtRequest.getAuthor_id());
List<WordTransformationTaskRequest> testP = wtRequest.getwt_task();
List<WordTransformation> thisIsIt = new ArrayList<WordTransformation>();
for(WordTransformationTaskRequest task : testP) {
WordTransformation send = new WordTransformation();
send.setBody(task.getBody());
send.setResult(task.getResult());
send.setWord(task.getWord());
send.setWordAtIndex(task.getWord_at_index());
thisIsIt.add(send);
}
wordTransformation.setwt_task(thisIsIt);
this.wtRepository.save(wordTransformation);
return wordTransformation;
}
This is my Entity:
#Entity
#Table(name = "wt_exercise")
public class WordTransformationExercise implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "author_id")
private Long authorId;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "wt_task",
joinColumns = #JoinColumn(name = "exercise_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "task_id", referencedColumnName = "task_id"))
private List<WordTransformation> wt_task;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public void setwt_task(List<WordTransformation> list) {
this.wt_task = list;
}
public Collection<?> getwt_task() {
return this.wt_task;
}
}
This is Task entity:
#Entity
#Table(name = "wt_task")
public class WordTransformation implements Serializable {
#Id
#Column(name = "task_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long task_id;
#Column(name = "body")
private String body;
#Column(name = "result")
private String result;
#Column(name = "word")
private String word;
#Column(name = "word_at_index")
private Integer wordAtIndex;
#Column(name = "exercise_id")
private Long exercise_id;
public void setExercise_id(Long exercise_id) {
this.exercise_id = exercise_id;
}
public Long getExercise_id() {
return exercise_id;
}
public void setId(Long task_id) {
this.task_id = task_id;
}
public Long getId() {
return task_id;
}
public void setBody(String body) {
this.body = body;
}
public String getBody() {
return body;
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
public void setWordAtIndex(Integer wordAtIndex) {
this.wordAtIndex = wordAtIndex;
}
public Integer getWordAtIndex() {
return wordAtIndex;
}
}
My API is returning 'id' and 'authorId' fine when I set wt_task to null
This is an example of my sql:
INSERT INTO wt_exercise (id, author_id) VALUES (2, 2);
INSERT INTO wt_task (body, result, word, word_at_index, exercise_id, task_id) VALUES ('please start ', 'running', 'run', 13, 2, 2);
It depends on what you are trying to do.
If you are trying to update an existing entity, you should retrieve it from your repository and set the values instead of creating a new object and trying to save it with an existing key.
If you are trying to create something new then don't set the key at all.

Hibernate #OneToMany #ManyToOne inserting into multiple tables

CREATE TABLE `Policy` (
`policyId` int(11) NOT NULL AUTO_INCREMENT,
`policyName` varchar(30) NOT NULL,
`roleId` int(11) NOT NULL,
PRIMARY KEY (`policyId`)
CONSTRAINT `policy_ibfk_1` FOREIGN KEY (`roleId`) REFERENCES `Role` (`roleId`) ON DELETE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `Role` (
`roleId` int(11) NOT NULL AUTO_INCREMENT,
`rolename` varchar(30) NOT NULL,
`roleDescription` varchar(100) DEFAULT NULL,
PRIMARY KEY (`roleId`),
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
I have a 1-Many mapping for the Role-Policy table described and the POJO as follows
#Entity
#Table(name="policy")
public class AWSPolicy implements Serializable{
#Id
#GeneratedValue
#Column(name = "policyId")
private int policyId;
#Column(name = "policyName")
private String policyName;
#ManyToOne
#JoinColumn(name="roleId")
private Role role;
public AWSRole getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public int getPolicyId() {
return policyId;
}
public void setPolicyId(int policyId) {
this.policyId = policyId;
}
public String getPolicyName() {
return policyName;
}
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
}
#Entity
#Table(name="role")
public class Role implements Serializable{
#Column(name = "rolename")
private String rolename;
#Id
#GeneratedValue
#Column(name = "roleId")
private int roleId;
#Column(name = "roleDescription")
private String roleDescription;
#OneToMany(cascade=CascadeType.PERSIST, mappedBy = "role")
private Set<AWSPolicy> policies;
public Set<AWSPolicy> getPolicies() {
return policies;
}
public void setPolicies(Set<AWSPolicy> policyList) {
this.policies = policyList;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public String getRoleDescription() {
return roleDescription;
}
public void setRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
}
}
The issue is that when I try to insert into the table , it inserts only into the Role table but not the policy table. Can someone help me with this.
Role role = new Role();
Set<Policy> policyList = new HashSet<Policy>();
Policy policy = new Policy();
policy.setPolicyName("uberpolicy");
policyList.add(policy);
role.setRolename("uberrole");
role.setRoleDescription("uberrole");
role.setPolicies(policyList);
Session session = getSessionFactory().getCurrentSession();
session.save(role);
May be this example will help you
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/
Can you please remove cascade=CascadeType.PERSIST and try.
Can you please write output of you query so I can help you.
I tried the code that you post. I see the insert queries being executed on the ROLE and POLICY tables but the value in roleId column of the POLICY table is null. This is because you have set the role object in the policy instance. You have to set both ends of a relationship.
The below code should update the foreign key value
Role role = new Role();
Set<Policy> policyList = new HashSet<Policy>();
Policy policy = new Policy();
policy.setPolicyName("uberpolicy");
policy.setRole(role); //Set the role object in the policy through a setter.
policyList.add(policy);
role.setRolename("uberrole");
role.setRoleDescription("uberrole");
role.setPolicies(policyList);
Session session = getSessionFactory().getCurrentSession();
session.save(role);
Below is the fix
#Entity
#Table(name="cas_aws_role")
public class AWSRole implements Serializable{
#Column(name = "casAWSRolename")
private String casAWSRolename;
#Id
#GeneratedValue
#Column(name = "casAWSRoleId")
private int casAWSRoleId;
#Column(name = "casAWSRoleDisplayName")
private String casAWSRoleDisplayName;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="casAWSRoleId")
private Set<AWSPolicy> policies = new HashSet<AWSPolicy>();
// method to manage the bidirectional association
public void addToPolicies(AWSPolicy awsPolicy) {
this.policies.add(awsPolicy);
awsPolicy.setAWSRole(this);
}
#ManyToOne
#JoinColumn(name="casAWSRolesetId")
private AWSRoleset awsRoleset;
public AWSRoleset getAWSRoleset() {
return awsRoleset;
}
public void setAWSRoleset(AWSRoleset awsRoleset) {
this.awsRoleset = awsRoleset;
}
public Set<AWSPolicy> getPolicies() {
return policies;
}
public void setPolicies(Set<AWSPolicy> policyList) {
this.policies = policyList;
}
public int getCasAWSRoleId() {
return casAWSRoleId;
}
public void setCasAWSRoleId(int casAWSRoleId) {
this.casAWSRoleId = casAWSRoleId;
}
public String getCasAWSRolename() {
return casAWSRolename;
}
public void setCasAWSRolename(String casAWSRolename) {
this.casAWSRolename = casAWSRolename;
}
public String getCasAWSRoleDisplayName() {
return casAWSRoleDisplayName;
}
public void setCasAWSRoleDisplayName(String casAWSRoleDisplayName) {
this.casAWSRoleDisplayName = casAWSRoleDisplayName;
}
}
#Entity
#Table(name="cas_aws_policy")
public class AWSPolicy implements Serializable{
#Id
#GeneratedValue
#Column(name = "casAWSPolicyId")
private int casAWSPolicyId;
#Column(name = "casAWSPolicyName")
private String casAWSPolicyName;
#ManyToOne
#JoinColumn(name="casAWSRoleId")
private AWSRole awsRole;
public AWSRole getAWSRole() {
return awsRole;
}
public void setAWSRole(AWSRole awsRole) {
this.awsRole = awsRole;
}
public int getCasAWSPolicyId() {
return casAWSPolicyId;
}
public void setCasAWSPolicyId(int casAWSPolicyId) {
this.casAWSPolicyId = casAWSPolicyId;
}
public String getCasAWSPolicyName() {
return casAWSPolicyName;
}
public void setCasAWSPolicyName(String casAWSPolicyName) {
this.casAWSPolicyName = casAWSPolicyName;
}
}

How to avoid any FK-entity loading, but still use FK-entity in HQL?

I have a parent entity DBParentEntity that have relation to FK-entity DBForeignEntity.
#Entity
#Table(catalog = "my_schema", name = "my_table")
public class DBParentEntity {
...
private DBForeignEntity foreign;
#ManyToOne
#JoinColumn(name = "foreign_id", referencedColumnName = "id")
public DBForeignEntity getForeign() {
return foreign;
}
public void setForeign(DBForeignEntity foreign) {
this.foreign = foreign;
}
}
How to avoid any loading FK-entity, but still use it in HQL?
I want to load foreign entity with my own cached method
private int foregnId;
#Basic
#Column(name = "foreign_id")
public int getForegnId() {
return foregnId;
}
public void setForegnId(int foregnId) {
this.foregnId = foregnId;
}
private DBForeignEntity foreign;
private boolean hasForeign;
#Transient
public DBForeignEntity getForeign() {
if (!hasForeign) {
initForeign();
}
return foreign;
}
#Transient
private synchronized void initForeign() {
if (hasForeign) return;
foreign = getFromCache(foregnId)
if (foreign!= null) hasForeign= true;
}
I can drop #ManyToOne annotation at all and replace it with #Transient,
but all relations HQL will fail:
Query query = session.createQuery("from DBParentEntity parent where parent.!foreign!.more_foregn.some_field = :some_value ")

hibernate association with n levels

I have two tables (ProspectMaster,ProspectContactsMaster). to maintain a relationship, I made a mapping table(ProspectContactsMap) using an embeddable entity(ProspectContactsMapID). Bellow are the all entities
#Entity
public class ProspectMaster {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int prospectID;
#Column(nullable=false)
#Length(max = 50)
private String companyName;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "prospectContactsMapID.prospectMaster", cascade=CascadeType.ALL)
private Set<ProspectContactsMap> prospectContactsMap = new HashSet<ProspectContactsMap>(0);
public int getProspectID() {
return prospectID;
}
public void setProspectID(int prospectID) {
this.prospectID = prospectID;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Set<ProspectContactsMap> getProspectContactsMap() {
return prospectContactsMap;
}
public void setProspectContactsMap(Set<ProspectContactsMap> prospectContactsMap) {
this.prospectContactsMap = prospectContactsMap;
}
}
#Entity
public class ProspectContactsMaster {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int prospectContactID;
#Length(max = 25)
private String firstName;
public int getProspectContactID() {
return prospectContactID;
}
public void setProspectContactID(int prospectContactID) {
this.prospectContactID = prospectContactID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
#Entity
#AssociationOverrides({
#AssociationOverride(name = "prospectContactsMapID.prospectMaster",
joinColumns = #JoinColumn(name = "prospectID")),
#AssociationOverride(name = "prospectContactsMapID.prospectContactsMaster",
joinColumns = #JoinColumn(name = "prospectContactID")) })
public class ProspectContactsMap {
#EmbeddedId
private ProspectContactsMapID prospectContactsMapID = new ProspectContactsMapID();
private int isMainContact;
#Transient
public ProspectMaster getProspectMaster() {
return this.getProspectContactsMapID().getProspectMaster();
}
public void setProspectMaster(ProspectMaster prospectMaster) {
getProspectContactsMapID().setProspectMaster(prospectMaster);
}
#Transient
public ProspectContactsMaster getProspectContactsMaster() {
return this.getProspectContactsMapID().getProspectContactsMaster();
}
public void setProspectContactsMaster(ProspectContactsMaster prospectContactsMaster) {
getProspectContactsMapID().setProspectContactsMaster(prospectContactsMaster);
}
public ProspectContactsMapID getProspectContactsMapID() {
return prospectContactsMapID;
}
public void setProspectContactsMapID(ProspectContactsMapID prospectContactsMapID) {
this.prospectContactsMapID = prospectContactsMapID;
}
public int getIsMainContact() {
return isMainContact;
}
public void setIsMainContact(int isMainContact) {
this.isMainContact = isMainContact;
}
}
#Embeddable
public class ProspectContactsMapID implements Serializable {
#ManyToOne
private ProspectMaster prospectMaster;
#ManyToOne
private ProspectContactsMaster prospectContactsMaster;
public ProspectMaster getProspectMaster() {
return prospectMaster;
}
public void setProspectMaster(ProspectMaster prospectMaster) {
this.prospectMaster = prospectMaster;
}
public ProspectContactsMaster getProspectContactsMaster() {
return prospectContactsMaster;
}
public void setProspectContactsMaster(ProspectContactsMaster prospectContactsMaster) {
this.prospectContactsMaster = prospectContactsMaster;
}
}
now my requirement is to fetch all prospect having company name starts with d or having main contacts starts with d. I have made a query, but in n level I can not provide association property. Bellow is my query
Disjunction disjOrCondition = Restrictions.disjunction();
Criteria cr = getCurrentSession().createCriteria(ProspectMaster.class);
cr.createAlias("prospectContactsMap", "prospectContact");
Criterion thirdCondition = Restrictions.conjunction().add(Restrictions.eq("prospectContact.isMainContact",1))
.add(Restrictions.like("prospectContact.prospectContactsMapID.prospectContactsMaster.firstName", searchVal.toString(),MatchMode.ANYWHERE));
disjOrCondition.add(Restrictions.like("companyName", searchVal.toString(),MatchMode.ANYWHERE));
disjOrCondition.add(thirdCondition);
if I run this, I get bellow exception
org.hibernate.QueryException: could not resolve property: prospectContactsMapID.prospectContactsMaster.firstName
can anyone please tell me where is the problem? and can anyone tell me any example on same. I want to use hql only.
From what I know I just can tell you 2 things:
you can try another fetching strategy; instead of LAZY you could try EAGER
there is a property in the configuration file: hibernate.max_fetch_depth, but i guess you are using the default. It sets the maximum depth for a single-ended asociation.

#ManyToMany with Hibernate and JPA

I have two tables that are bound by a ManyToMany relationship.
Table 1 is TimeSlot and has a collection of documents created in that time slot.
Table 2 is Documents and has a collection of TimeSlots as a given document could be modified many times in different timeslots.
In this particular program for each document I find or create a document row for it. Further I find or create a time slot that represents the epoch of the action, create, update, delete. Note: delete is an event performed on the document, not on the row that represents it. In this program there are no deletes or removes performed against any row of either table.
However I am seeing as many deletes against the timeslot_document mapping table as there are inserts.
My question is this, why is Hibernate issuing deletes? It appears to be related to dirty update processing. By why repeated deletes from timeslot where id=1?
When I had OneToMany I didn't see the deletes but the model was inaccurate then (as you might imagine).
For every document I determine the date (hour accuracy only) that the action occured on, increment a tally and add the document to the collection.
Something else curious is I implement MVCC via the #Version annotation yet in a 'show innodb status\G' I see the table locked. At this moment there is one row for timeslot, 1988 documents tallied in it and the version of the row is at 1999. The table locking is concerning me.
Here is the main code fragment:
for (Eventlog event : eventsList) {
currentEvent = event.getEventId();
String tmp = formatter.format(event.getEpoch());
Date epoch = null;
try {
epoch = formatter.parse(tmp);
} catch (ParseException ex) {
Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
}
cal.setTime(epoch);
Tuple tuple = holding.get(epoch);
if (tuple == null) {
tuple = new Tuple();
holding.put(epoch, tuple);
}
queryTimeSlot.setParameter("docType", docType);
queryTimeSlot.setParameter("date", epoch);
try {
ats = (TimeSlot)queryTimeSlot.getSingleResult();
insertATS = false;
} catch (Exception e) {
insertATS = true;
ats = new TimeSlot();
atsk = new TimeSlotKey();
atsk.setSlotDate(epoch);
atsk.setDocType(docType);
ats.setHour(cal.get(Calendar.HOUR_OF_DAY));
ats.setSlotKey(atsk);
}
if (processMM) {
queryDocument.setParameter("id", event.getUpdEventLogDocId());
queryDocument.setParameter("doc", docType);
try {
doc = (Document)queryDocument.getSingleResult();
insertDoc = false;
} catch (Exception e) {
doc = new Document();
docKey = new DocumentKey();
docKey.setDocid(event.getUpdEventLogDocId());
docKey.setType(docType);
doc.setDocKey(docKey);
insertDoc = true;
}
}
try {
ats.getDocuments().add(doc);
} catch (Exception e) {
Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, "{0}", e);
System.exit(-1);
}
if (processMM) {
doc.getTimes().add(ats);
}
TimeSlot Entity
#Entity
#Table(name = "TimeSlot", catalog = "Analytics")
public class TimeSlot implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Basic(optional=false)
#Column(name="id")
private Integer id;
#Basic(optional = false)
#Column(name = "slotKey")
private TimeSlotKey slotKey;
#Basic(optional = false)
#Column(name = "slotHour")
private int slotHour;
#Basic(optional = false)
#Column(name = "inserts")
private int inserts;
#Basic(optional = false)
#Column(name = "deletes")
private int deletes;
#Basic(optional = false)
#Column(name = "active")
private int active;
#ManyToMany(fetch=FetchType.LAZY)
#JoinColumn(name="doc_id")
private Collection<Document> documents;
#Basic(optional = false)
#Version
#Column(name = "version")
private int version;
public TimeSlot() {
documents = new ArrayList<Document>(0);
}
public Collection<Document> getDocuments() {
return documents;
}
public void setDocuments(Collection<Document>documents) {
this.documents = documents;
}
public int getHour() {
return slotHour;
}
public void setHour(int slotHour) {
this.slotHour = slotHour;
}
#Override
public int hashCode() {
int hash = 0;
hash += (slotKey != null ? slotKey.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof ActivityTimeSlot)) {
return false;
}
}
Documents follows:
#Entity
#Table(name = "Documents", catalog = "Analytics")
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Basic(optional=false)
#Column(name="id")
private Integer id;
#Basic(optional = false)
#Column(name = "docKey")
private DocumentKey docKey;
#Basic(optional = false)
#Column(name = "inserts")
private int inserts;
#Basic(optional = false)
#Column(name = "deletes")
private int deletes;
#ManyToMany(fetch=FetchType.LAZY, mappedBy="")
#JoinColumn(name="slot_id")
private Collection<TimeSlot> times;
#Basic(optional = false)
#Version
#Column(name = "version")
private int version;
public Document() {
times = new ArrayList<TimeSlot>(0);
inserts = 0;
deletes = 0;
}
#Override
public int hashCode() {
return docKey.hashCode();
}
#Override
public boolean equals(Object object) {
return docKey.equals(object);
}
public int getDeletes() {
return deletes;
}
public void setDeletes(int deletes) {
this.deletes = deletes;
}
public void incrDeletes() {
deletes++;
}
public void incrInserts() {
inserts++;
}
public int getInserts() {
return inserts;
}
public void setInserts(int inserts) {
this.inserts = inserts;
}
public Pair getPair() {
return new Pair(inserts, deletes);
}
#Override
public String toString() {
return docKey.toString();
}
public Collection<ActivityTimeSlot> getTimes() {
return times;
}
public void setTimes(Collection<ActivityTimeSlot>times) {
this.times = times;
}
public DocumentKey getDocKey() {
return docKey;
}
public void setDocKey(DocumentKey docKey) {
this.docKey = docKey;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
New info
I happened across this
ManyToMany assoicate delete join table entry
which is almost identical. It's just I don't understand Arthur's answer. Also I noticed in the mysql innodb status it is doing an outer left join...is that really necessary?
So in EntityA I should have a method add(EntityB) and in EntityB I should have a method called add(EntityA) in these methods I
public void add(EntityB entity) {
entity.getList().add(this);
getList().add(entity);
}
I am not seeing how this is functionally different than what I have.

Categories