How to add list of Strings to entity - Spring, Hibernate - java

I have Spring Boot project with DB. I've already get table, let's call it "People". I need to add a second table "People_Strings" with two columns: People_id and String. I need to include many strings for every row from People.
How can I map it in my People entity in project?
Edit: I need to do this without creating separete class for String or for People_Strings

If you only need that, you can add the following property to the People entity class:
#ElementCollection
public List<String> strings;

What you need is #OneToMany relation between people and strings. Something like the following will work for you.
#Entity
#Table(name = "People")
public class People{
#Id
#GeneratedValue
private Long id;
#OneToMany(fetch= FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "peopleId")
private List<PeopleStrings> PeopleStrings;
#Entity
#Table(name = "People_Strings")
public class PeopleStrings{
#Id
#GeneratedValue
private Long peopleId;
#ManyToOne
#JoinColumn(name="peopleId")
private String string;

You'll want a #OneToMany relationship on the Person object (please don't use plurals, eg People). And possibly a #ManyToOne relationship on the PersonString object (again no plurals)
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/OneToMany.html
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/ManyToOne.html

This is kinda basic question and I suggest you to read Hibernate "Get Started" first. (one-to-many / many-to-one relations especially)

Related

How to Implement Many To Many for Spring and Hibernate?

I would like to implement this relationship in Java Spring and Hibernate:
In my GnrlOrgChargeCode class, I have:
#OneToMany (targetEntity=IOrgChargeCodeCond.class, mappedBy="gnrlOrgChargeCode", fetch=FetchType.EAGER)
private List <IOrgChargeCodeCond> orgChargeCodeConds;
and in my OrgChargeCodeCond class, I have:
#ManyToOne
private IGnrlOrgChargeCode gnrlOrgChargeCode;
#OneToMany
private List <IBillingCondition> billingCondition;
and in my BillingCondition class:
#OneToMany
private List <OrgChargeCodeCond> orgChargeCodeCond;
and in my OrgChargeCodeRule class:
#ManyToOne
private BillingRule billingRule;
and in my BillingRule class:
#OneToMany(mappedBy = "billingRule")
private List<OrgChargeCodeRule> orgChargeCodeRules;
But when I startup Tomcat, I get this error:
Could not determine type for: java.util.Set, at table: ORG_CHARGE_CODE_COND, for columns: [org.hibernate.mapping.Column(billingCondition)]
My query is this:
select from GnrlOrgChargeCode gocc
join OrgChargeCodeRule occr
join BillingRule br
join OrgChargeCodeCond occc
join BillingCondition bc
where gocc.orgId = ?
assuming gocc.orgId is valid and there are rows in gocc.
Please help. thanks.
I think here is the problem:
OrgChargeCodeCond:
#OneToMany
private List <IBillingCondition> billingCondition;
BillingCondition:
#OneToMany
private List <OrgChargeCodeCond> orgChargeCodeCond;
So you are actually defining a #OneToMany relation in both directions. From your diagram the BillingCondition should have #ManyToOne.
If you need a many-to-many relationship, you can try to make this work with #ManyToMany annotations on both sides. But I wouldn't recommend it, better add another entity and create #OneToMany in between.
Another "pro tipp", have a look at https://bootify.io, you can create or import your schema and get out your Hibernate entities.

JPA: How do I set up an entity with several children and several parents of same entity type?

I'm trying to model a business entity, where said business can have several parent businesses and several child businesses. I'm not sure which relationships are suited, or even what mapping is appropriate. I'm familiar with SQL but new to ORM in Java.
My thinking is that a business can have many or none children, and a business can have many or none parents. Therefore I've tried setting both as OneToMany but also as OneToMany, both resulting in this error: Illegal use of mappedBy on both sides of the relationship.
The implementation:
#Entity
public class Business{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy = "parentOrgs")
private Collection<Business> chlidOrgs;
#OneToMany(mappedBy = "chlidOrgs")
private Collection<Business> parentOrgs;
// --- Getters and setters below ---
What am I not understanding here? Any and all help much appreciated.
Your current mapping is syntactically incorrect, because only one side of the relationship can be owning side. Owning side is the field defined by value of mappedBy attribute. More detailed explanation can be found from here.
Also removing mappedBy from the one side does not solve the problem, because counterpart of OneToMany must be ManyToOne. Removing it from the both sides leaves us with two unirectional associations, which is also not what is needed.
Because each Business can have multiple parents and it seems to be preferred to be able to navigate directly to the childrens as well, solution is to use bidirectional ManyToMany:
#Entity
public class Business {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToMany(mappedBy = "parents")
private Collection<Business> childrens;
#ManyToMany
private Collection<Business> parents;
}
From database point of view this means following tables:
Business(id)
Business_Business(childrens_id, parents_id)
When necessary, name of the join table and columns can be controlled via JoinTable.

Is it possible to force Hibernate to embed an Entity?

In my use-case, I would like to #Embedded a class C in an entity.
Another entity refers to C with #OneToMany association and therefore C is annotated with #Entity.
I am aware that this seems like bad design, yet I believe that it makes perfect sense in my case.
Is it possible to force Hibernate to embed an Entity? If I try it, Hibernate complains about a missing setter for the id property of C.
I think the problem comes from this:
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
Why not just create the entity that you want, and in that entity, embed C as well. That way you have C in both classes, one as embedded and another as embedded of the new entity.
#Embeddable
public class Contact {
private String firstname;
private String lastname;
// getters and setters removed.
}
and here is your embedding class:
#Entity
public class Student {
#Embedded
private Contact contact;
}
and here is the new entity that embeds contact also
#Entity
public class FirmContact {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int contactId;
#Embedded
private Contact contact;
}
And finally the class that insists the contact must be an entity:
#Entity
public class Business {
#OneToOne(cascade=CascadeType.ALL)
private FirmContact contacts;
}
It'll just be a couple of extra steps in java to populate the object, but it should do the mapping you want. I hope this helps.
Hibernate doesn't allow you to treat an Embeddable as an Entity or to embed an Entity. According to Hibernate types:
an Embeddable, doesn't have an identifier, since it's state is part of an owning Entity.
an Entity cannot be embedded, because each Entity has a distinct life-cycle.
Since another class already has a #OneToMany association to class C, it's obvious you cannot turn it into an Embeddable.
More, a bidirectional #OneToMany association will perform better than an embeddable collection.
What you can do, is to use it as a #OneToOne association in the entity where you wanted to embed the C entity. You can make that target entity be the owning side of the association so that the C association is bound to the target entity life-cycle.

Hibernate - User and his Report list

I have an entity named User. I decided that every user has its `Report (also entity) list. Then I created something like this:
#Entity
#Table(name="user")
public class User implements Serializable{
#Id
#GeneratedValue
private long id;
...
#ElementCollection
private List<Report> reportList;
Now the Report object looks like this:
#Entity
#Table(name = "report")
public class Report implements Serializable{
#Id
#GeneratedValue
private long id;
...
#ManyToOne
private User reporter;
Is it right approach? Every user can have many reports, but every report can belong to only one user.
I thought about changing #ElementCollection to #ManyToOne, but I think I prefer operating on a list.
The main problem is, how to make relation(connection) between user and their reports?
No, it's not the right approach. ElementCollection is for a collection of simple types (String dates, etc.) or embeddable types. For a collection of entities, you need a OneToMany association (which is quite normal, given that you have a ManyToOne in the other direction):
one user has many reports
many reports are reported by one user
.
#OneToMany(mappedBy = "reporter")
private List<Report> reportList;
The documentation covers this in detail.

How can I map double relationships JPA?

I need map at JPA something like this:
How I can map two relationships between two "tables", one of them is primary key and one to one (newClient in advance) and in the other side, a one to many that aint PK?
I tried something like this but it fails.
public class Recommendation implements Serializable {
#Id #OneToOne
#Column(name="...")
private Client newClient;
#ManyToOne
#Column(name="...")
private Client oldFella;
#Column(name="...")
private Boolean wasUsedToGenerateBond;
...
}
Thanks!
it is possible to have multiple ManyToMany relationships between two entities. Each relationship would have its own join table. The default name of the join table may be the same, so you would need to specify the #JoinTable's name.
possible answer here
JPA Problems mapping relationships
more information
Hibernate 4.2, bidirectional #OneToOne and #Id
Like this:
#Id #OneToOne
#JoinColumn(name="id_client1")
private Client newClient;
#ManyToOne
#JoinColumn(name="id_client2")
private Client oldFella;

Categories

Resources