Hibernate mapping map with #OneToMany bidirectional association - java

I have query problem when trying to use entities with bidirectional associations.
I have an entity Wallet that has some relations to two other entities. There is a problem with the relation to the entity WalletBranchOffice. If I comment this part of code, everything works fine. Here are my entities:
Wallet.java
#Entity
#Table(name="WALLET", schema=SchemasConfig.SCHEMA_NEW)
#Cacheable(true)
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Wallet implements Serializable {
private static final long serialVersionUID = 3307006915060155334L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="WALLET_ID")
private Integer walletId;
public Integer getWalletId() {
return walletId;
}
#Column(name="INTERNAL_REFERENCE", nullable=false, length=32)
private String internalReference;
public String getInternalReference() {
return internalReference;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="CURRENCY_ID", nullable=false)
private Currency currency;
public Currency getCurrency() {
return currency;
}
#Column(name = "CACHE_AMOUNT_SUM", nullable = false, precision = 13, scale = 2)
private BigDecimal cacheAmountSum;
public BigDecimal getCacheAmountSum() {
return cacheAmountSum;
}
#OneToMany(mappedBy="wallet", fetch=FetchType.EAGER)
#MapKeyColumn(name="BRANCH_OFFICE_ID")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
private Map<Integer, WalletBranchOffice> walletBranchOffices;
public Map<Integer, WalletBranchOffice> getWalletBranchOffices() {
return walletBranchOffices;
}
#OneToMany(mappedBy="wallet", fetch=FetchType.EAGER)
#MapKeyColumn(name="WALLET_PREV_ID")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
/*
* wallets which must be used before current wallet
*/
private Map<Integer, WalletDependency> walletDependencies;
public Map<Integer, WalletDependency> getWalletDependencies() {
return walletDependencies;
}
#OneToMany(mappedBy="walletPrev", fetch=FetchType.EAGER)
#MapKeyColumn(name="WALLET_ID")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
/*
* wallets that can be used after current wallet
*/
private Map<Integer, WalletDependency> dependentWallets;
public Map<Integer, WalletDependency> getDependentWallets() {
return dependentWallets;
}
#Column(name = "TEXT_KEY")
private String textKey;
public String getTextKey() {
return textKey;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((walletId == null) ? 0 : walletId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Wallet other = (Wallet) obj;
if (walletId == null) {
if (other.walletId != null)
return false;
} else if (!walletId.equals(other.walletId))
return false;
return true;
}
}
WalletBranchOffice.java
#Entity
#Table(name="WALLET_BRANCH_OFFICE", schema=SchemasConfig.SCHEMA_NEW)
#Cacheable
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
#Immutable
public class WalletBranchOffice implements Serializable {
private static final long serialVersionUID = 9135909966091486878L;
#Id
#Column(name="WALLET_BRANCH_OFFICE_ID")
private Integer walletBranchOfficeId;
public Integer getWalletBranchOfficeId() {
return walletBranchOfficeId;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="WALLET_ID", nullable=false)
private Wallet wallet;
public Wallet getWallet() {
return wallet;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="BRANCH_OFFICE_ID", nullable=false)
private BranchOffice branchOffice;
public BranchOffice getBranchOffice() {
return branchOffice;
}
#Column(name="CREATE DATETIME")
#Type(type="com.uniqagroup.ims.common.EETDateType$TimestampType")
private Timestamp createDatetime;
public Timestamp getCreateDatetime() {
return createDatetime;
}
}
Here is WalletDependency.java with which there is no problem.
#Entity
#Table(name="WALLET_DEPENDENCY",schema=SchemasConfig.SCHEMA_NEW)
#Cacheable
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
#Immutable
public class WalletDependency implements Serializable {
private static final long serialVersionUID = -6665047739101469610L;
#Id
#Column(name="WALLET_DEPENDENCY_ID")
private Integer walletRequiredId;
public Integer getWalletRequiredId() {
return walletRequiredId;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="WALLET_ID", nullable=false)
private Wallet wallet;
public Wallet getWallet() {
return wallet;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="WALLET_PREV_ID",nullable=false)
private Wallet walletPrev;
public Wallet getWalletPrev() {
return walletPrev;
}
}
And my problem is that if I perform even a simple select query like:
List<Wallet> wallets = em.createQuery("FROM Wallet AS w",Wallet.class).getResultList();
with EntityManager, I'm getting a SQL syntax error:
Caused by: java.sql.SQLSyntaxErrorException: [SQL0199] Keyword AS not expected. Valid tokens: , FROM INTO.
at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:852) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:692) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:662) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1763) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.AS400JDBCPreparedStatement.<init>(AS400JDBCPreparedStatement.java:354) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:2166) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:2108) [jt400-7.9_jdbc4.0.jar:JTOpen 7.9]
at org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnection.doPrepareStatement(BaseWrapperManagedConnection.java:732)
at org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnection.prepareStatement(BaseWrapperManagedConnection.java:707)
at org.jboss.jca.adapters.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:404)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161) [hibernate-core-4.2.0.Final-redhat-1.jar:4.2.0.Final-redhat-1]
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182) [hibernate-core-4.2.0.Final-redhat-1.jar:4.2.0.Final-redhat-1]
... 163 more

No need for AS:
List<Wallet> wallets = em.createQuery("FROM Wallet w",Wallet.class).getResultList();
Some examples:
http://docs.oracle.com/javaee/6/tutorial/doc/bnbrg.html

Thank you for your replays!!! After printing out generated SQL I found the problem. It is just a stupid technical error. There is missing "_" sign in mapping createDatetime property to create_datetime column in WalletBranchOffice entity.
#Column(name="CREATE DATETIME")

Related

insertable=false puts null into my value, but true gives an error (many to many relationship)

I have 3 tables. Hospitals and doctors. The 3rd table is a junction table of both that contains id,ids of 2 other tables as foreign keys and few other columns. When trying to put record to a junction table I got an error that one of foreign keys have to be set with insertable=false. However when I set it like this then I get that the value can't be null (since my database requires that field).I'm stuck and can't go any further with those 2 errors.
If I manage to avoid those 2 errors then I get an erorr that there is an unknown column in the field list.
Doctors entity:
#Entity
#Table(name = "doctors")
public class Doctors implements Serializable {
private Integer id;
private String name;
private String surname;
private String title;
private String licenseNumber;
private String phone;
private String email;
private String nationality;
private String speciality;
private LocalDate dateOfBirth;
private Boolean isATeacher;
private List<HospitalDoctors> hospitalDoctors = new LinkedList<>();
//consturctors
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "Idd", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//setters and getters for rest of the fields with #column annotations on getters
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.doctor", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
public List<HospitalDoctors> getHospitalDoctors() {
return hospitalDoctors;
}
public void setHospitalDoctors(List<HospitalDoctors> hospitalDoctors) {
this.hospitalDoctors = hospitalDoctors;
}
Hospitals entity:
#Entity
#Table(name = "hospitals")
public class Hospitals implements Serializable {
private Integer id;
private String name;
private String country;
private String town;
private String street;
private String postalCode;
private String phoneNumber;
private String faxNumber;
private Integer numberOfAmbulances;
private Boolean helicopterAccess;
private Boolean teachingHospital;
private List<HospitalDoctors> hospitalDoctors = new LinkedList<>();
//constructors
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "Idh", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//getters setters with #column annotations over getters
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.hospital", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
public List<HospitalDoctors> getHospitalDoctors() {
return this.hospitalDoctors;
}
public void setHospitalDoctors(List<HospitalDoctors> hospitalDoctors) {
this.hospitalDoctors = hospitalDoctors;
}
Junction table entity:
#Entity
#Table(name = "hospitaldoctors")
#AssociationOverrides({
#AssociationOverride(name = "pk.hospital",
joinColumns = #JoinColumn(name = "Idh")),
#AssociationOverride(name = "pk.doctor",
joinColumns = #JoinColumn(name = "Idd"))
})
public class HospitalDoctors implements Serializable {
private Integer id;
private Integer idH;
private Integer idD;
private HospitalDoctorsId pk = new HospitalDoctorsId();
private LocalDate contractStartDate;
private LocalDate contractEndDate;
private String position;
private Boolean supervisor;
private Boolean partTime;
//constructors
#Column(name ="Idhos")
public Integer getIdH() {
return this.idH;
}
public void setIdH(Integer idH) {
this.idH = idH;
}
#Column(name ="Iddoc")
public Integer getIdD() {
return this.idD;
}
public void setIdD(Integer idD) {
this.idD = idD;
}
#EmbeddedId
public HospitalDoctorsId getPk() {
return pk;
}
public void setPk(HospitalDoctorsId pk) {
this.pk = pk;
}
#Transient
public Hospitals getHospital(){
return getPk().getHospital();
}
public void setHospital(Hospitals hospital){
getPk().setHospital(hospital);
}
#Transient
public Doctors getDoctor(){
return getPk().getDoctor();
}
public void setDoctor(Doctors doctor){
getPk().setDoctor(doctor);
}
//rest of the setters getters with #Column
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HospitalDoctors that = (HospitalDoctors) o;
if(getPk() != null?!getPk().equals(that.getPk()) : that.getPk() != null) return false;
return true;
}
#Override
public int hashCode() {
return (getPk() != null? getPk().hashCode() : 0);
}
Junction table Id:
#Embeddable
public class HospitalDoctorsId implements Serializable {
private Hospitals hospital;
private Doctors doctor;
#ManyToOne
public Hospitals getHospital() {
return hospital;
}
public void setHospital(Hospitals hospital) {
this.hospital = hospital;
}
#ManyToOne
public Doctors getDoctor() {
return doctor;
}
public void setDoctor(Doctors doctor) {
this.doctor = doctor;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HospitalDoctorsId that = (HospitalDoctorsId) o;
if(hospital != null?!hospital.equals(that.hospital) : that.hospital != null) return false;
if(doctor != null?!doctor.equals(that.doctor) : that.doctor != null) return false;
return true;
}
#Override
public int hashCode() {
int result;
result = (hospital != null? hospital.hashCode() : 0);
result = 31* result + (doctor != null? doctor.hashCode() : 0);
return result;
}
}
I expected to be able to add records to junction table in data base in form fields I have foreign keys for hospital and doctors id to put in as well as other fields. Unfortunately I get either error that say to put foreign keys columns idD and idH as insertable, updatable false which leads to null value being passed which gives another error. When I solve those errors I get the error:
java.sql.SQLSyntaxErrorException: Unknown column 'hospitaldo0_.Idd' in 'field list'when trying to display records nad unknown column Idd when trying to add record (displaying works when Im getting insertable error or null value error. adding never works)
If I remember correctly, you need to have a single #ManyToMany relation rather than two #OneToMany relations.

EntityNotFoundException unable to find entity with id X after using MappedSuperclass

Environment:
javaee 7
java 8
jpa 2
I got the error EntityNotFoundException when I make a query of Moviment and automatically tries to load the associated Espai after I have modifed Espai class to separate id and version in a separate class with the annotation #MappedSuperclass.
I can suspect that it is something related with equals() and hashCode() methods but I have not been able to figure out the problem.
Espai that works fine
#Entity
#Table(name = "a_espai")
public class Espai implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String nom;
private Integer version;
#ManyToOne
#JoinColumn(name = "idServei", referencedColumnName = "id")
private Servei servei;
...
#Override
public int hashCode() {
int hash = servei == null ? 1 : servei.getId();
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Espai)) {
return false;
}
Espai other = (Espai) obj;
return id != null && id.equals(other.getId());
}
}
Espai after change that provokes the error
#Entity
#Table(name = "a_espai")
public class Espai extends BaseEntity implements Serializable {
private String nom;
#ManyToOne
#JoinColumn(name = "idServei", referencedColumnName = "id")
private Servei servei;
#Override
public int hashCode() {
int hash = 0;
if (servei == null) {
return hash;
} else {
return servei.getId();
}
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Espai)) {
return false;
}
Espai other = (Espai) obj;
return getId() != null && getId().equals(other.getId());
}
}
Moviment class where Espai gets the error on eager loading
#Entity
#Table(name = "t_moviment")
public class Moviment extends BaseEntity implements Serializable {
private LocalDate dataInici;
private LocalDate dataFi;
private String observacio;
#ManyToOne
#Basic(optional = false)
#JoinColumn(name = "idEspai", referencedColumnName = "id")
private Espai espai;
...
}
**Espai before change that provokes the error**
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Version
protected Integer version;
public Integer getId() {
return id;
}
}

hibernate how to extend one entity to all the entities

I have two fields that should appear in each table. So I wanted to create an entity that will hold these fields and the rest of my entities inherited these fields
But when I run the query I get the error - org.hibernate.QueryException: could not resolve property: active of: com.db.tables.PersonTable
what i'm doing wrong?
Base class all entities should inherit these fields
#XmlRootElement
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class BaseTable implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "Updated")
#JsonProperty
#NotNull
protected Timestamp updated;
#Column(name = "Active")
#JsonProperty
#NotNull
protected byte active;
public BaseTable ()
{
active = (byte)1;
updated = DbUtils.getCurrentTimeStamp();
}
public byte getActive()
{
return active;
}
public void setActive(byte active)
{
this.active = active;
}
public Timestamp getUpdated()
{
return updated;
}
public void setUpdated(Timestamp updated)
{
this.updated = updated;
}
#Override
public String toString()
{
return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString();
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + active;
result = prime * result + ((updated == null) ? 0 : updated.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BaseTable other = (BaseTable) obj;
if (active != other.active) return false;
if (updated == null)
{
if (other.updated != null) return false;
}
else if (!updated.equals(other.updated)) return false;
return true;
}
}
A class that inherits
#Entity(name = "Persons")
#Table(name = "Persons")
public class PersonTable extends BaseTable implements Serializable
{
private static final long serialVersionUID = -5793514680136648542L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PersonId")
private short personId;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="personId")
PortalUserTable portalUser;
//getters&settersand more fields
}
one more class that inherits
#Entity(name = "PortalUser")
#Table(name = "PortalUser")
public class PortalUserTable extends BaseTable implements Serializable
{
private static final long serialVersionUID = -5793514680136648542L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PersonId")
private short personId;
#OneToOne
(mappedBy = "portalUser")
PersonTable person;
//getters&settersand more fields
}
the query
public ObjectDaoResponse getAllTigrisUsers() throws JsonProcessingException
{
try
{
Query q = sessionFactory.getCurrentSession().createQuery("SELECT new com.db.queries.users.User( u.portalUserId ,p.personName) FROM PortalUsers u INNER JOIN u.person p WHERE portalUserId = p.personId AND p.active = 1 AND u.active = 1");
List<TigrisUser> l = q.list();
return ObjectDaoResponse.getAnOkResponse(l);
}
catch(Exception e)
{
System.out.println(e);
return ObjectDaoResponse.getGeneralFailureResponse();
}
}
#MappedSuperclass
public class BaseTable ...
I would suggest to change naming convention Base(Table) -> Base(Entity). Do the same for all entity classes.
You should take care of inheritance strategy - https://en.wikibooks.org/wiki/Java_Persistence/Inheritance

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 ")

Issues while trying to create a hibernate query that navigates through many-to-many associations with additional join table entity and composite key

I have three entities: Account, AccountAttribut and Attribut. Account and Attribut are associated via AccountAttribut in a many-to-many relationship like it is described here (1). AccountAttribut is a join table entity that holds an additional attribute.
I try to build a HQL string that delivers all Accounts with the "wert"-property "John" in AccountAttribut and the name-property "FirstName" in Attribut.
I dont find the right HQL string. Can you help me out?
(1): http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/ "Mapping a many-to-many join table with extra column using JPA"
I tried this query:
List<Account> queried_accounts = HibernateUtils.queryList(
session.createQuery(""
+ "from Account as acc"
+ " full join acc.accountAttributes as accAtt"
+ " inner join accAtt.aa_pk.attribut as attr"
+ " where attr.name='FirstName' and accAtt.wert='John'")
);
and i get this error message:
ERROR: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'full outer join account_attribut accountatt1_ on
account0_.account_id=accountatt' at line 1
UPDATE:
I changed the query to:
List<Account> queried_accounts = HibernateUtils.queryList(
session.createQuery(""
+ "from Account as acc"
+ " inner join acc.accountAttributes as accAtt"
+ " inner join accAtt.aa_pk.attribut as attr"
+ " where attr.name='FirstName' and accAtt.wert='John'")
);
This seems to work.
But now i got a new Problem: queried_accounts does not seem to be a List of Accounts. If i get an object out of queried_accounts and try to apply account methods on it, i get an Exception at runtime.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
com.computacenter.qct.pojos.Account
These are relevant code extracts:
Account:
#Entity
#Table(name = "account")
public class Account {
private Long accountId;
private List<AccountAttribut> accountAttributes = new LinkedList<AccountAttribut>();
private Person person;
private Zielsystem zielsystem;
public Account() {
}
#Id
#GeneratedValue
#Column(name = "account_id", nullable = false)
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "aa_pk.account", cascade = {
CascadeType.PERSIST, CascadeType.MERGE })
#Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
public List<AccountAttribut> getAccountAttributes() {
return accountAttributes;
}
public void setAccountAttributes(List<AccountAttribut> accountAttribute) {
this.accountAttributes = accountAttribute;
}
#ManyToOne
#JoinColumn(name = "person_id")
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
#ManyToOne
#JoinColumn(name="zielsystem_id")
public Zielsystem getZielsystem() {
return zielsystem;
}
public void setZielsystem(Zielsystem zielsystem) {
this.zielsystem = zielsystem;
}
}
AccountAttribut:
#Entity
#Table(name="account_attribut")
#AssociationOverrides({
#AssociationOverride(name="aa_pk.account", joinColumns = #JoinColumn(name="account_id")),
#AssociationOverride(name="aa_pk.attribut", joinColumns = #JoinColumn(name="attribut_id"))
})
public class AccountAttribut {}
private AccountAttributPk aa_pk = new AccountAttributPk();
#Column(name="wert")
private String wert;
#EmbeddedId
public AccountAttributPk getAa_pk() {
return aa_pk;
}
public void setAa_pk(AccountAttributPk aa_pk) {
this.aa_pk = aa_pk;
}
#Transient
public Account getAccount() {
return getAa_pk().getAccount();
}
public void setAccount(Account account) {
getAa_pk().setAccount(account);
}
#Transient
public Attribut getAttribut() {
return getAa_pk().getAttribut();
}
public void setAttribut(Attribut attribut) {
getAa_pk().setAttribut(attribut);
}
public String getWert() {
return wert;
}
public void setWert(String wert) {
this.wert = wert;
}
public boolean equals(Object o) {
if (this== o) return true;
if (o ==null|| getClass() != o.getClass()) return false;
AccountAttribut that = (AccountAttribut) o;
if (getAa_pk() !=null?!getAa_pk().equals(that.getAa_pk()) : that.getAa_pk() !=null) return false;
return true;
}
public int hashCode() {
return (getAa_pk() !=null? getAa_pk().hashCode() : 0);
}
}
AccountAttributPk:
public class AccountAttributPk implements Serializable {
private static final long serialVersionUID = -1551814445010872872L;
private Account account;
private Attribut attribut;
#ManyToOne
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#ManyToOne
public Attribut getAttribut() {
return attribut;
}
public void setAttribut(Attribut attribut) {
this.attribut = attribut;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AccountAttributPk that = (AccountAttributPk) o;
if (account != null ? !account.equals(that.account) : that.account != null)
return false;
if (attribut != null ? !attribut.equals(that.attribut)
: that.attribut != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (account != null ? account.hashCode() : 0);
result = 31 * result + (attribut != null ? attribut.hashCode() : 0);
return result;
}
}
Attribut
#Entity
#Table(name="Attribut")
public class Attribut {
private Long attributId;
private String name;
private List<PersonAttribut> personenAttribute = new LinkedList<PersonAttribut>();
private List<AccountAttribut> accountAttribute = new LinkedList<AccountAttribut>();
private List<BerechtigungsobjektAttribut> berechtigungsobjektAttribute = new LinkedList<BerechtigungsobjektAttribut>();
public Attribut() {}
public Attribut(String name) {
this.name = name;
}
#Id
#GenericGenerator(name="generator", strategy="increment")
#GeneratedValue(generator="generator")
#Column(name="attribut_id", nullable=false)
public Long getAttributId() {
return attributId;
}
public void setAttributId(Long attributId) {
this.attributId = attributId;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pa_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<PersonAttribut> getPersonenAttribute() {
return personenAttribute;
}
public void setPersonenAttribute(List<PersonAttribut> personenAttribute) {
this.personenAttribute = personenAttribute;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "aa_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<AccountAttribut> getAccountAttribute() {
return accountAttribute;
}
public void setAccountAttribute(List<AccountAttribut> accountAttribute) {
this.accountAttribute = accountAttribute;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "ba_pk.attribut", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
public List<BerechtigungsobjektAttribut> getBerechtigungsobjektAttribute() {
return berechtigungsobjektAttribute;
}
public void setBerechtigungsobjektAttribute(
List<BerechtigungsobjektAttribut> berechtigungsobjektAttribute) {
this.berechtigungsobjektAttribute = berechtigungsobjektAttribute;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object other) {
if (other == null)
return false;
if (this == other)
return true;
if (this.getClass() != other.getClass())
return false;
final Attribut otherAccount = (Attribut) other;
return EqualsUtils.nullSafeEquals(this.getName(), otherAccount.getName());
}
#Override
public int hashCode() {
final int PRIME = 42;
return this.name.hashCode() * PRIME;
}
}

Categories