Create relation between tables in JPA - java

I have main table merchants and second table terminals:
Merchant table:
#Entity
#Table
public class Merchants {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#Column
private String name;
#Column
private String login;
}
Terminal table:
#Entity
#Table
public class Terminals {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#Column
private int merchant_id;
#Column
private String mode;
}
I want to set merchant_id into table Terminals. I suppose that many to many will be proper relation. How I can create it?

If you have a Join Table:
On Merchants class:
#ManyToMany
#JoinTable(name="MER_TER", joinColumns=#JoinColumn(name="MERCH_ID", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="TERM_ID", referencedColumnName="id"))
private List<Terminals> terminalsList;
On Terminals class:
#ManyToMany(mappedBy="terminalsList")
private List<Merchants> merchantsList;
Page of reference: link
If you don't have a Join Table, try to look here: https://stackoverflow.com/a/25018992

Related

JPA entity with join column but not persisted

I have to entities
#Table(name = "BD_PERSON")
public class DBPerson {
#Id
#Column(name = "persion_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "car_id")
private Long car_id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "car_id", referencedColumnName = "car_id", insertable = false, updatable = false)
private DBCar car;
#Column(name = "label")
private String label;
and
#Table(name = "BD_CAR")
public class DBCar {
#Id
#Column(name = "car_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "car_number")
private Integer carNumber;
#Column(name = "description")
private String description;
I want to be able to get the Person with the car entity but this should not persist to the database when updating.
But i should be able to update the car_id by itself as it relates the the id in the car table.
but when i try to test this by setting only the car_id i receive an Referential integrity constraint violation.
Because the car_id (FK)references the car_id (PK)
Is there any better way to accomplish what im trying to do?
The database already exists and is configured like this where the car_id is not an actual foreign key

How can I do the multiply relations in Hibernate?

everyone! Sorry but I need some help. My db is looking this way, I try to do same throught the Hibernate in Java.
But I don`t understand how I need to annoted this relations with so many different tables.
It`s a part of my Abiturient table.
#Entity
#Table (name = "abiturient",
uniqueConstraints = {#UniqueConstraint(columnNames = {"id"})})
public class Abiturient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
#ManyToOne
private Long id;
#Column
private Date data_narodjennya;
#Column
private Integer city_village;
It`s a part of my nomer_telefonu table
#Entity
#Table(name = "nomer_telefonu")
public class NomerTelefonu {
#Id
#Column(name = "nomer_tel_id", nullable = false, unique = true, length = 11)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long nomer_tel_id;
#Column(name = "nomer")
private String nomer;
#Column(name = "id")
#OneToMany(fetch = FetchType.LAZY)
private Set<Abiturient> id;
I don`t think that all there is right, `cos every time I try to solve problem I get an error and need other type.
Use #OneToMany bidirectional relation.
#Entity
public class Abiturient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy = "abiturent")
private List<NomerTelefonu> phones = Lists.newArrayList();
}
#Entity
public class NomerTelefonu{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "nomer_tel_id")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private Abiturient abiturent;
}
Lists.newArrayList() from guava. This is working mapping. Always use the simplest version to experiment.
what is #JoinColumn and how it is used in Hibernate
You can use this project to play with mappings in the unit tests:
https://github.com/v-ladynev/hibernate-experimental

How to use uniqueConstraint on referenced table column with JPA

How can I include a referenced table column in a unique constraint? I want to create a unique constraint for table Survey for columns toEmail, receipt.receiptSeries and receipt.receiptNum.
See entities below please:
Receipt
#Entity
#Table(name = "RECEIPT")
public class Receipt {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "RECEIPT_SERIES")
private String receiptSeries;
#Column(name = "RECEIPT_NUM")
private String receiptNum;
}
Survey
#Entity
#Table(name = "SURVEY"}
public class Survey {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#ManyToOne(optional = false)
#JoinColumn(name = "RECEIPT_ID")
private Receipt receipt;
#Column(name = "TO_EMAIL")
private String toEmail;
}
I've tried using the approach below with no success:
#Table(name = "SURVEY", uniqueConstraints = {
#UniqueConstraint(columnNames = {"TO_EMAIL", "RECEIPT.RECEIPT_SERIES", "RECEIPT.RECEIPT_NUM"})})
Using a composite primary key with receiptSeries and receiptNum for Receipt is not an option.
Try something like this
#Table(name="notification_status", uniqueConstraints=
arrayOf(UniqueConstraint(columnNames= arrayOf("external_user_id",
"external_organization_id",
"notification_id"))))

Joining with cross-reference table in hibernate and spring

I use hibernate and spring-data. There are two tables with many-to-many relationship.
#Entity
#Table(name = "FirstEntity")
public class FirstEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "first_entity_id")
private Long id;
#Column(name = "first_entiry_name")
private String name;
/* getters and setters are below*/
}
#Entity
#Table(name = "SecondEntity")
public class SecondEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "second_entity_id")
private Long id;
#Column(name = "second_entiry_name")
private String name;
#Column(name = "second_entiry_desc")
private String description;
/* getters and setters are below*/
}
And entity for cross-reference table.
#Entity
#Table(name = "FirstSecondEntity")
public class FirstSecondEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "first_second_entity_id")
private Long id;
#Column(name = "first_entity_id")
private Long firstEntityId;
#Column(name = "second_entity_id")
private Long secondEntityId;
/* getters and setters are below*/
}
I need SELECT like this
SELECT FirstEntity.name, SecondEntity.name, SecondEntity.description FROM SecondEntity INNER JOIN FirstSecondEntity ON SecondEntity.id = FirstSecondEntity.secondEntityId INNER JOIN User ON FirstEntity.id = FirstSecondEntity.firstEntityId
i.e. I need all records from cross-reference table where instead of ids there is actual info from entities.
Inserting this query into #Query annotation in my CrudRepository-extended class doesn't work because of
ERROR [main][org.hibernate.hql.internal.ast.ErrorCounter] Path expected for join!
So I need your help.
Your join table is all screwed up. In this case, you actually don't even need the join table as a hibernate mapping:
In Second Entity add the following list:
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "FirstSecondEntity",
joinColumns = {
#JoinColumn(name = "first_entity_id",
nullable = false,
updatable = false) },
inverseJoinColumns = {
#JoinColumn(name = "second_entity_id",
nullable = false,
updatable = false) },
)
private List<FirstEntity> firstEntities;
In FirstEntity add the following list:
#ManyToMany(fetch = FetchType.LAZY,
mappedBy = "firstEntities")
private List<SecondEntity> secondEntities;

Hibernate one-to-one, No row with the given identifier exists exception

I need a link between two entities, so I use a one-to-one
#Entity
#Table(name = "T_USER")
public class User implements Serializable {
#Id
#Column(name = "user_id")
private int userId;
#Column(name = "login")
private String login;
#OneToOne(optional = true)
#JoinColumn(name="login", referencedColumnName="person_id", nullable = true, insertable = false, updatable = false)
private Person person;
}
#Entity
#Table(name = "T_PERSON")
public class Person implements Serializable {
#Id
#Column(name = "person_id")
private String personId;
#Column(name = "pin")
private String pin;
}
If there is no item for a particulary PERSON in table T_USER, user.getPerson throw a exception:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [packagename.com.entity.Person#scabriou]
But If I have reference between the 2 tables in the db, the getter works!
I can't say if this the best solution but you could use the #NotFound annotation. E.g.
#NotFound(action = NotFoundAction.IGNORE)
private Person person;
I believe person will remain null and the exception will not be thrown.

Categories

Resources