Hibernate OneToMany relationship mapping clarification - java

I have configured the OneToMany mappings for my tables.So when inserting values to the fisrt table on second time it gives me an error Cannot insert duplicate key row in object. Here is my tables.
Table -1 (feature_id is pk and auto generated by table) and name is inserting by me.
Feature_id(PK)
Name
feature table has index
"GO
CREATE UNIQUE INDEX idx_Name ON "dbo"."Feature"(Name)
Table-2 (Feature_Version_id PK and auto generated by table)
Feature_Version_id ,
Version_Name
Feature_id
POJO classes are :
#Entity
#Table(name="FEATURE")
public class Feature {
private int feature_id;
private String name;
private Set<FeatureVersion> featureversion = new HashSet<FeatureVersion>(0);
public Feature() {
}
public Feature(String name ,Set<FeatureVersion> featureversion) {
this.name = name;
this.featureversion = featureversion;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="FEATURE_ID")
public int getFeature_id() {
return feature_id;
}
public void setFeature_id(int feature_id) {
this.feature_id = feature_id;
}
#Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch=FetchType.LAZY,mappedBy="feature")
public Set<FeatureVersion> getFeatureversion() {
return featureversion;
}
public void setFeatureversion(Set<FeatureVersion> featureversion) {
this.featureversion = featureversion;
}
}
Second table POJO class:
#Entity
#Table(name="FEATURE_VERSION")
public class FeatureVersion {
private int feature_version_id;
private String version_name;
private int feature_id;
private Feature feature;
private Set<PartFeatureVersion> partfeatureversion = new HashSet<PartFeatureVersion>(0);
public FeatureVersion() {
}
public FeatureVersion(Feature feature, String version_name, int feature_id) {
this.feature = feature;
this.version_name = version_name;
this.feature_id = feature_id;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="FEATURE_VERSION_ID")
public int getFeature_version_id() {
return feature_version_id;
}
public void setFeature_version_id(int feature_version_id) {
this.feature_version_id = feature_version_id;
}
#Column(name="VERSION_NAME")
public String getVersion_name() {
return version_name;
}
public void setVersion_name(String version_name) {
this.version_name = version_name;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="feature_id")
public Feature getFeature() {
return feature;
}
public void setFeature(Feature feature) {
this.feature = feature;
}
#OneToMany(fetch=FetchType.LAZY,mappedBy="featureversion")
public Set<PartFeatureVersion> getPartfeatureversion() {
return partfeatureversion;
}
public void setPartfeatureversion(Set<PartFeatureVersion> partfeatureversion) {
this.partfeatureversion = partfeatureversion;
}
}
Main class :
Session session = (Session) HibernateUtil.getSessionFactory().openSession();
Feature feature = new Feature();
FeatureVersion featurever = new FeatureVersion();
feature.setName("stack");
session.save(feature);
featurever.setVersion_name("12.2");
featurever.setFeature(feature);
feature.getFeatureversion().add(featurever);
session.save(featurever);
session.getTransaction().commit();
session.flush();
Here is my input values :
(feature id generated by table)
First attempt for first table: stack
First attempt for second table : 12.2
(feature_id come from feature table)
second attempt for first table: stack
second attempt for second table : 12.3
OneToMany configuration will take care if more than one values come to OneToMany releationship ? Or i need to check if value is exist then just the version name ? These all values loop through from the list. Please advise what should i do here .
Thanks,

Related

JPA createQuery where condition does not work

I am trying to use JPA to fetch records from database. However I am able to insert records indatabse and even get all the records using createQuery method of class EntityManager.
But in below case I am not getting why the condition in where clause is not working.
Please help me figure it out.
POJO class :
#Entity
#Table(name = "frameworks_filter")
public class FilteredFrameworksDbStructure {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "regular_name")
private String regularName;
#Column(name = "component_name")
private String componentName;
#Column(name = "component_owner")
private String componentOwner;
#Column(name = "frameworks")
private String frameworks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRegularName() {
return regularName;
}
public void setRegularName(String regularName) {
this.regularName = regularName;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getComponentOwner() {
return componentOwner;
}
public void setComponentOwner(String componentOwner) {
this.componentOwner = componentOwner;
}
public String getFrameworks() {
return frameworks;
}
public void setFrameworks(String frameworks) {
this.frameworks = frameworks;
}
}
DAO class method:
public List<FilteredFrameworksDbStructure> getFilteredFrameworks(String regularName) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
List<FilteredFrameworksDbStructure> filteredFrameworksDbStructureList = entityManager
.createQuery("from FilteredFrameworksDbStructure F where F.regularName = :regular", FilteredFrameworksDbStructure.class)
.setParameter("regular", regularName)
.getResultList();
return filteredFrameworksDbStructureList;
}
Issue : Condition in where clause does not work. It simply fetch all the records irrespective of the regularName provided.
Regards,
Parag Vinchurkar
Why don't you use the JpaRepository or CrudRepository to fetch your results? Check out this tutorial here and here on how to use them.
And you can use your where clause. Please see below the example repository you can use to obtain the same results as the entityManager
public interface FilteredFrameworksDbStructureRepo extends JpaRepository<FilteredFrameworksDbStructure , Integer>{
List<FilteredFrameworksDbStructure> findAllByRegularName(String regularName)
}
Please note that you will have to change your id member variable from int to Integer

Getting entity from table without having primary key in Hibernate

I'm currently working on a project where I'm trying to get a list of enities from table which does not have a primary key (dk_systemtherapie_merkmale). This table is 1:n related to another table (dk_systemtherapie). See the screenshot for the table structure.
When getting an entry for dk_systemtherapie, the program fetches the Collection "dkSystemtherapieMerkmalesById". However, the first table entry is fetched as often as the number of actual entries in the table is. It never fetches the other entries from dk_systemtherapie_merkmale. I assume it has something to do with the fact that hibernate can't differ between the entries, but I don't know how to fix it.
Table schema
I've created two corresponding entity classes, dk_systemtherapie:
#Entity
#Table(name = "dk_systemtherapie", schema = "***", catalog = "")
public class DkSystemtherapieEntity {
private int id;
private Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(mappedBy = "dkSystemtherapieByEintragId")
public Collection<DkSystemtherapieMerkmaleEntity> getDkSystemtherapieMerkmalesById() {
return dkSystemtherapieMerkmalesById;
}
public void setDkSystemtherapieMerkmalesById(Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById) {
this.dkSystemtherapieMerkmalesById = dkSystemtherapieMerkmalesById;
}
}
Here the second one, which is accessing the table without a primary key, dk_systhemtherapie_merkmale:
#Entity #IdClass(DkSystemtherapieMerkmaleEntity.class)
#Table(name = "dk_systemtherapie_merkmale", schema = "***", catalog = "")
public class DkSystemtherapieMerkmaleEntity implements Serializable {
#Id private Integer eintragId;
#Id private String feldname;
#Id private String feldwert;
private DkSystemtherapieEntity dkSystemtherapieByEintragId;
#Basic
#Column(name = "eintrag_id")
public Integer getEintragId() {
return eintragId;
}
public void setEintragId(Integer eintragId) {
this.eintragId = eintragId;
}
#Basic
#Column(name = "feldname")
public String getFeldname() {
return feldname;
}
public void setFeldname(String feldname) {
this.feldname = feldname;
}
#Basic
#Column(name = "feldwert")
public String getFeldwert() {
return feldwert;
}
public void setFeldwert(String feldwert) {
this.feldwert = feldwert;
}
#Id
#ManyToOne
#JoinColumn(name = "eintrag_id", referencedColumnName = "id")
public DkSystemtherapieEntity getDkSystemtherapieByEintragId() {
return dkSystemtherapieByEintragId;
}
public void setDkSystemtherapieByEintragId(DkSystemtherapieEntity dkSystemtherapieByEintragId) {
this.dkSystemtherapieByEintragId = dkSystemtherapieByEintragId;
}
}
I assume the problem is releated to the fact that Hibernate is using the following annotation as the one and only id for fetching data from database.
#Id
#ManyToOne
#JoinColumn(name = "eintrag_id", referencedColumnName = "id")
public DkSystemtherapieEntity getDkSystemtherapieByEintragId() {
return dkSystemtherapieByEintragId;
}
This leads to the problem that when getting more than one entry with the same id (as the id is not unique), you will get the number of entries you would like to but hibernate is always fetching the first entry for this id. So in fact you are getting dublicate entries.
So how to fix this?
According to this question: Hibernate and no PK, there are two workarounds which are actually only working when you don't have NULL entries in your table (otherwise the returning object will be NULL as well) and no 1:n relationship. For my understanding, hibernate is not supporting entities on tables without primary key (documentation). To make sure getting the correct results, I would suggest using NativeQuery.
Remove the Annotations and private DkSystemtherapieEntity dkSystemtherapieByEintragId; (incl. beans) from DkSystemtherapieMerkmaleEntity.java und add a constructor.
public class DkSystemtherapieMerkmaleEntity {
private Integer eintragId;
private String feldname;
private String feldwert;
public DkSystemtherapieMerkmaleEntity(Integer eintragId, String feldname, String feldwert) {
this.eintragId = eintragId;
this.feldname = feldname;
this.feldwert = feldwert;
}
public Integer getEintragId() {
return eintragId;
}
public void setEintragId(Integer eintragId) {
this.eintragId = eintragId;
}
public String getFeldname() {
return feldname;
}
public void setFeldname(String feldname) {
this.feldname = feldname;
}
public String getFeldwert() {
return feldwert;
}
public void setFeldwert(String feldwert) {
this.feldwert = feldwert;
}
}
Remove private Collection<DkSystemtherapieMerkmaleEntity> dkSystemtherapieMerkmalesById; (incl. beans) from DkSystemtherapieEntity.java.
Always when you need to get entries for a particular eintrag_id, use the following method instead of the Collection in DkSystemtherapieEntity.java.
public List<DkSystemtherapieMerkmaleEntity> getDkSystemtherapieMerkmaleEntities(int id) {
Transaction tx = session.beginTransaction();
String sql = "SELECT * FROM dk_systemtherapie_merkmale WHERE eintrag_id =:id";
List<Object[]> resultList;
resultList = session.createNativeQuery(sql)
.addScalar("eintrag_id", IntegerType.INSTANCE)
.addScalar("feldname", StringType.INSTANCE)
.addScalar("feldwert", StringType.INSTANCE)
.setParameter("id", id).getResultList();
tx.commit();
List<DkSystemtherapieMerkmaleEntity> merkmale = new ArrayList<>();
for (Object[] o : resultList) {
merkmale.add(new DkSystemtherapieMerkmaleEntity((Integer) o[0], (String) o[1], (String) o[2]));
}
return merkmale;
}
Call getDkSystemtherapieMerkmaleEntities(dkSystemtherapieEntityObject.getid()) instead of getDkSystemtherapieMerkmalesById().

Null columns are created on either tables when accessing data using Spring Data JPA

I am new to Spring Data JPA and Hibernate. By looking at different examples I built a working model for CRUD operations on one entity, I am having trouble in joining two tables to extract AF_NAME using AF_ID from another table which is Foreign key. A null column is created with the names of and while accessing, null is returned.please check if I am following preocedure for joins and point me to any tutorial know.
I followed this solution and still there is no progress.
#Entity
#Configuration
#EnableAutoConfiguration
#Table(name = "AFF_CONFIG")
public class AFF_CONFIG implements Serializable {
#Id
#Column(name = "AFF_CONFIG_ID")
private String AFF_CONFIG_ID;
#Column(name = "AFF_ID")
private String AFF_ID;
#Column(name = "CH_ID")
private String CH_ID;
#Column(name = "M_ID")
private Long M_ID;
#Column(name = "KEY")
private String KEY;
#Column(name = "VALUE")
private String VALUE;
#Column(name = "SYSTEM")
private String SYSTEM;
private AFF aff;
#LazyCollection(LazyCollectionOption.TRUE)
#ManyToOne
#JoinColumn(name = "AFF_ID")
public AFF getAff() {
return aff;
}
public void setAffiliate(AFF aff) {
this.aff = aff;
}
public String getAFF_CONFIG_ID() {
return AFF_CONFIG_ID;
}
public void setAFF_CONFIG_ID(String aFF_CONFIG_ID) {
AFF_CONFIG_ID = aFF_CONFIG_ID;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = AFF_ID;
}
public String getCH_ID() {
return CH_ID;
}
public void setCHANNEL_ID(String cH_ID) {
CH_ID = cH_ID;
}
public Long getM_ID() {
return M_ID;
}
public void setM_ID(Long m_ID) {
M_ID = m_ID;
}
public String getKEY() {
return KEY;
}
public void setKEY(String kEY) {
KEY = kEY;
}
public String getVALUE() {
return VALUE;
}
public void setVALUE(String vALUE) {
VALUE = vALUE;
}
public String getSYSTEM() {
return SYSTEM;
}
public void setSYSTEM(String sYSTEM) {
SYSTEM = sYSTEM;
}
Second entity is:
#Entity
#Table(name = "AFF")
public class AFF implements Serializable {
#Column(name = "AFF_NAME")
private String AFF_NAME;
#Column(name = "AFF_CODE")
private String AFF_CODE;
#Id
#Column(name = "AFF_ID")
private String AFF_ID;
private Set<AFF_CONFIG> someAff = new HashSet<AFF_CONFIG>();
#LazyCollection(LazyCollectionOption.TRUE)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "aff")
public Set<AFF_CONFIG> getSomeAff() {
return someAff;
}
public void setSomeAff(Set<AFF_CONFIG> someAff) {
this.someAff = someAff;
}
public String getAFF_ID() {
return AFF_ID;
}
public void setAFF_ID(String aFF_ID) {
AFF_ID = aFF_ID;
}
public String getAFF_NAME() {
return AFF_NAME;
}
public void setAFF_NAME(String aFF_NAME) {
AFF_NAME = aFF_NAME;
}
public String getAFF_CODE() {
return AFF_CODE;
}
public void setAFF_CODE(String aFF_CODE) {
AFF_CODE = aFF_CODE;
}
Since this is many to one relation I created set type in one and object type in another as defined in other places.Created a repository by extending crud and added a query. Excise the bunch of different annotations, I included them in hoping to solve the null entry.
#Repository
public interface MarketRepository extends CrudRepository<AFF_CONFIG,String> {
Page<AFF_CONFIG> findAll(Pageable pageable);
#Query("Select a,b from AFF_CONFIG a, AFF b where a.AFF_ID = b.AFF_ID" )
public List<AFF_CONFIG> getAffData();
}
the applicatoin is working fine even after some tinkering until I Included these annotations. Now there is this error:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: aff.
I solved the issue with the help of my Supervisor. Looks like we have to follow naming specifications for Class and variables. And one more correction is to remove collection type object and change it to just object (removed set in aff class).I will post the corrected later, to compare and contrast.

Error while binding form request play-framework 2.5.4

I am using play-framework-java 2.5.4.
I want to bind a user-input-from values to my model class variables.
This is my controller function that except form POST :
public Result formSubmit()
{
MlmModel mlmModel;
play.data.Form<MlmModel> form = play.data.Form.form(MlmModel.class).bindFromRequest();
mlmModel = form.get();
mlmModel.save();
mlmModel.callUpdate();
return ok(Json.toJson(mlmModel));
}
But I am getting this error
[CompletionException: java.lang.IllegalStateException: Error(s) binding form: {"parent_id":["Invalid value"]}]
because, one of my input field is not compulsory to fill by user.
It's fine if user left blank some fields.
But my code should
save all data that user provides to database and
should save 0 by default for the fields left blank by user .
I am Using play-Eben and my database server is MySQL 5.x
How can I achieve this?
Edit 1 :
MlmModel.java
#Entity
public class MlmModel extends Model
{
#Id
#GeneratedValue()
public Long ID;
public Logic logic;
public MlmModel() {
this.parent_id = 0;
logic = new Logic(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String name;
public long getParent_id() {
return parent_id;
}
public void setParent_id(long parent_id) {
if (String.valueOf(parent_id).isEmpty())
this.parent_id = 0;
this.parent_id = parent_id;
}
#Column(columnDefinition = "long default 0")
public long parent_id;
#Formats.DateTime(pattern="dd/MM/yyyy")
public Date created_time = new Date();
public Long balance = new Long(0);
public static Finder<Long, MlmModel> find = new Finder<Long,MlmModel>(MlmModel.class);
public List<ValidationError> validate()
{
List<ValidationError> errors = new ArrayList<ValidationError>();
if (Long.toString(parent_id).isEmpty())
parent_id = 0;
if (errors.isEmpty())
return null;
else
return errors;
}
}

How to Represent Composite keys in Hibernate using Annotations?

So I reverse engineered some tables from my db and when I try to save my object to the db I get the following error:
Initial SessionFactory creation failed.org.hibernate.AnnotationException: A Foreign key refering com.mycode.Block from com.mycode.Account has the wrong number of column. should be 2
Exception in thread "main" java.lang.ExceptionInInitializerError
The Domain objects Are Block which contains a number of Account Objects:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "Block")
public Set<EAccount> getAccounts() {
return this.Accounts;
}
Account has a Composite key of Id and Role. This has been setup in a seperate Class:
#Embeddable
public class BlockAccountId implements java.io.Serializable {
private long blockOid;
private String accountRole;
public BlockAccountId() {
}
public BlockAccountId(long blockOid, String accountRole) {
this.blockOid = blockOid;
this.accountRole = accountRole;
}
#Column(name = "BLOCK_OID", nullable = false)
public long getBlockOid() {
return this.blockOid;
}
public void setBlockOid(long blockOid) {
this.blockOid = blockOid;
}
#Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
public String getAccountRole() {
return this.accountRole;
}
public void setAccountRole(String accountRole) {
this.accountRole = accountRole;
}
So I want to know. How can I Link the tables Block and account on blockOid but still ensure the account table has both blockOid and accountRole as a composite key.
Any examples would be greatly appreciated!
N.B this is a Block (One) to Account (Many) relationship.
Thanks
The easiest is to place your association directly in the embedded id component.
Hibernate reference documentation
Section 5.1.2.1.1. id as a property using a component type ()
Example (Only write the important getter() and setter())
#Entity
public class Block {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="BLOCK_OID")
long blockOid;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "id.block", cascade=CascadeType.ALL)
Set<Account> accounts = new HashSet<Account>();
}
#Entity
public class Account {
#EmbeddedId BlockAccountId id;
public Account()
{
this.id = new BlockAccountId();
}
public void setBlock(Block pBlock) {
this.id.setBlock(pBlock);
}
public Block getBlock() {
return this.id.getBlock();
}
public String getAccountRole() {
return this.id.getAccountRole();
}
public void setAccountRole(String accountRole) {
this.id.setAccountRole(accountRole);
}
}
#Embeddable
public class BlockAccountId implements java.io.Serializable {
#ManyToOne(optional = false)
private Block block;
#Column(name = "ACCOUNT_ROLE", nullable = false, length = 10)
private String accountRole;
public BlockAccountId() {
}
//Implement equals and hashcode
}
The corresponding database table are :
CREATE TABLE block (
BLOCK_OID bigint(20) NOT NULL auto_increment,
PRIMARY KEY (`BLOCK_OID`)
)
CREATE TABLE account (
ACCOUNT_ROLE varchar(10) NOT NULL,
block_BLOCK_OID bigint(20) NOT NULL,
PRIMARY KEY (`ACCOUNT_ROLE`,`block_BLOCK_OID`),
KEY `FK_block_OID` (`block_BLOCK_OID`),
CONSTRAINT `FK_block_OID` FOREIGN KEY (`block_BLOCK_OID`) REFERENCES `block` (`BLOCK_OID`)
)
based on hibernate documentation here's the link
based on it you can do the following :
#Entity
public class Account {
#EmbeddedId BlockAccountId id;
#MapsId(value = "blockOid")
#ManyToOne
private Block block;
public Account()
{
this.id = new BlockAccountId();
}
public void setBlock(Block pBlock) {
this.block = pBlock;
}
public Block getBlock() {
return this.block;
}
public String getAccountRole() {
return this.id.getAccountRole();
}
public void setAccountRole(String accountRole) {
this.id.setAccountRole(accountRole);
}
}

Categories

Resources