I have two entities, let's name them University and Student, Student is unidirectional ManyToOne with University they both extends base class BasicUUIDEntity:
#MappedSuperclass
public class BasicUUIDEntity implements Serializable {
protected UUID id;
#Id
#Column(name = "id", columnDefinition = "binary(16)")
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BasicUUIDEntity that = (BasicUUIDEntity) o;
return id == null || id.equals(that.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
The structure of Student and University doesn't really matters, the important things is:
Student.class:
#Entity
#Table(name = "students")
public static class Student extends BasicUUIDEntity {
private University univ;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "univ_id", referencedColumnName = "id")
public University getUniversity() {
return univ;
}
public void setUniversity(University univ) {
this.univ = univ;
}
}
University.class:
#Entity
#Table(name = "universities")
public static class University extends BasicUUIDEntity {
//of course it does contain some fields, but they are strings, etc.
}
The tables are created as follows:
CREATE TABLE students
(
id BINARY(16) NOT NULL,
univ_id BINARY(16),
PRIMARY KEY (id),
CONSTRAINT FK_STUDENT_UNIV
FOREIGN KEY (univ_id) REFERENCES memory_type (id)
ON DELETE SET NULL
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
CREATE TABLE universities
(
id BINARY(16) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
The Issue is sometimes, on really rare occasions Hibernate doesn't extract that University entity along with Student, meaning that when I do student.getUniversity() it returns null, and in debugger it is also null. BUT the students table contains exactly the same univ_id as expected University of this student, and so does university contains that id. I am completely sure that hibernate session is not closed, and I've tried to execute exactly the same query as hibernate does, and it does return expected id of the university, joins them, etc. The thing is that most of the time It does work well, and such issue happens very rarely due to unknown reasons, what is more strange is that the table does contains that id, so it seems like it is not an MySQL issue.
Also worth mention, I am using Spring Data JPA.
Have anyone encountered such behavior? Could it be due to Inheritance/Data JPA/Java 9/Anything other?
PS.
Please ignore any typo in the code, it is just an example
Versions:
Hibernate: 5.2.12.Final,
Spring Data JPA: 2.0.5.RELEASE,
HikariCP: 2.7.8,
MySQL connector: 6.0.6,
Java: 9
MySQL: Ver 14.14 Distrib 5.7.21
Solved, finally
tl;dr
Put fetch = FetchType.LAZY to ManyToOne relation, so in my example it becomes:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "univ_id", referencedColumnName = "id")
public University getUniversity() {
return univ;
}
Description
I am not still sure why it behaves like this, but it seems that Hibernate does not extract many-to-one relations at all, if they're eager. It have some sense as this way there will be circular dependencies, but I thought that PersistenceSet will deal with such issues. What is even more strange - just the same structure actually works without eager extraction if I use Long instead of UUID.
Related
I am trying to create a very simple Spring Boot application for storing sports data.
It has two entities: player and tournament. However, I want to store how each player placed in each tournament.
For this, I created the following ER Diagram. The junction table PlayerPlacement_map contains a relationship-attribute placement for storing how the players place in a tournament:
I have followed this guide on how to map the relationship between Players and Tournament, with Id from those two tables as a composite key in the junction table called PlayerPlacementMap: https://www.baeldung.com/jpa-many-to-many
That has given me the following classes:
Player.java (Tournament.java follows a similar pattern - left out for brevity)
#Entity
#Table(name = "players")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id", updatable = false, nullable = false)
private long id;
#Column(name = "Name")
private String name;
#ManyToMany
#JoinTable(
name = "PlayerTournament_map",
joinColumns = #JoinColumn(name = "Player_Id"),
inverseJoinColumns = #JoinColumn(name = "Tournament_Id"))
Set<Tournament> attendedTournaments;
#OneToMany(mappedBy = "player")
Set<PlayerPlacement> placements;
//getters, constructors - left out for brevity
}
PlayerPlacementKey.java (making an embeddable composite key-class)
#Embeddable
public class PlayerPlacementKey implements Serializable {
#Column(name = "Player_Id")
long playerId;
#Column(name = "Tournament_Id")
long tournamentId;
//getters, setters, constructors, equals, hashcode - left out for brevity
}
PlayerPlacement.java (junction table)
#Entity
#Table(name = "PlayerPlacement_map")
public class PlayerPlacement {
#EmbeddedId
PlayerPlacementKey id;
#ManyToOne
#MapsId("PlayerId")
#JoinColumn(name = "Player_Id")
Player player;
#ManyToOne
#MapsId("TournamentId")
#JoinColumn(name = "Tournament_Id")
Tournament tournament;
int placement;
//constructors - left out for brevity
}
I have repositories for player, tournament and playerplacement. Player and tournament repositories are working fine on their own, and I am able to perform CRUD operations through a #RestController against a MSSQL database.
This is the repository for playerplacement:
#Repository
public interface PlayerPlacementRepository extends JpaRepository<PlayerPlacement, PlayerPlacementKey>
{}
For the junction table, I have made a PlayerPlacementController:
#RestController
public class PlayerPlacementController {
#Autowired
private PlayerPlacementRepository playerPlacementRepository;
#PostMapping("/playerplacement")
public PlayerPlacement addPlayerPlacement(#RequestBody PlayerPlacement playerPlacement) {
return playerPlacementRepository.save(playerPlacement);
}
}
Finally, here comes the problem: When I call the /"playerplacement" endpoint, I receive the following error:
org.hibernate.id.IdentifierGenerationException: null id generated for:class com.testproject.learning.model.PlayerPlacement
I think I have migrated the database just fine, but just to be safe, here is my migration for the junction table:
CREATE TABLE PlayerPlacement_map (
PlayerId Bigint NOT NULL,
TournamentId Bigint NOT NULL,
Placement int
CONSTRAINT PK_PlayerPlacement NOT NULL IDENTITY(1,1) PRIMARY KEY
(
PlayerId,
TournamentId
)
FOREIGN KEY (PlayerId) REFERENCES Players (Id),
FOREIGN KEY (TournamentId) REFERENCES Tournaments (Id)
);
I haven't been able to figure out what I am doing wrong. I appreciate all help and pointers that I receive - thanks in advance.
EDIT:
Progress has been made with help of user Alex V., but I hit a new problem as of right now.
I make the following JSON call:
{
"player":
{
"name":"John Winther"
},
"tournament":
{
"name":"Spring Boot Cup 2020"
},
"placement":3
}
I don't set the id (composite key) myself - I guess it should be handled by something of the framework? Anyways, when I make this call in debug mode, I get the following debug variables set in the endpoint:
However, it results in the following error:
java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "o" is null, which probably refers to my equals-method in PlayerPlacementKey.java (?):
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PlayerPlacementKey)) return false;
PlayerPlacementKey that = (PlayerPlacementKey) o;
return playerId == that.playerId &&
tournamentId == that.tournamentId;
}
Hope anybody can push me in the right direction one more time.
Your entity has playerId field annotated as #Column(name = "Player_Id"), but database table contains PlayerId column instead of Player_Id. The same situation with tournamentId, player, tournament fields.
#MapsId("TournamentId") has to contain #EmbededId class field name tournamentId instead of TournamentId. It means the field is mapped by embeded id field tournamentId.
#ManyToOne
#MapsId("tournamentId")
#JoinColumn(name = "tournamentId")
Tournament tournament;
The same problem here #MapsId("PlayerId") .
So after some research, I could not find something relevant.
I use one table as below:
#Table(name="product")
public class Product {
#Id
#GeneratedValue
private long productId;
// other irrelevant columns and code goes here
}
Now, I want to create another table that it goes like:
To make that, I tried something like this by following other examples or samples:
#Table(name="combined_products")
public class CombinedProducts {
#EmbeddedId
protected CombinedProductsPK bridgeId;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "product_1", referencedColumnName = "product_id"),
#JoinColumn(name = "product_2", referencedColumnName = "product_id")
})
#Column(name = "notes")
private String notes;
public ProductMatrix() {
bridgeId = new CombinedProductsPK();
}
// irrelevant code again
}
and the CombinedProductsPK:
#Embeddable
public class CombinedProductsPK implements Serializable {
public Long product_1;
public Long product_2;
public CombinedProductsPK() {}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
CombinedProductsPK b = (CombinedProductsPK)obj;
if (b == null) {
return false;
}
return b.product_1.equals(product_1) && b.product_2.equals(product_2);
}
#Override
public int hashCode() {
return (int)(product_1 + product_2);
}
}
and all seems to work perfect.
BUT, my problem is, when I take a look at the database and specific to the combined_products table, there is no FOREIGN_KEY constraint. Is there any way to describe this constraint in Java, or I must manually, in the Java part, take care of this??
This is how my table looks like in the MySQLWorkbench
CREATE TABLE `combined_products` (
`product_1` bigint(20) NOT NULL,
`product_2` bigint(20) NOT NULL,
`notes` varchar(255) DEFAULT NULL,
PRIMARY KEY (`product_1`,`product_2`)
)
I'm in a dead end here, so maybe I follow a wrong route. Every recommendation is accepted! Thanks in advance...
i didn't got what you mean. but maybe you need to try #JoinTable for that ?
enter link description here
i hope it helps.
I have a (abbreviated) class that looks like this:
#Entity
#Table
#SecondaryTable(
name = "SUPER_ADMIN",
pkJoinColumns = #PrimaryKeyJoinColumn(
name = "PERSON_ID",
referencedColumnName = "PERSON_ID"))
public class Person {
#Id
#Column(name = "PERSON_ID")
private Long personId;
// getters/setters omitted for brevity
}
The SUPER_ADMIN table has only one column: PERSON_ID. What I would like to do is add private Boolean superAdmin to Person where it would be true if the PERSON_ID is present in that table.
Is this even possible? I am using Hibernate as my JPA provider, so I'm open to proprietary solutions as well.
UPDATE
It seems like I should have done more homework. After poking around, I see that #SecondaryTable does inner joins and not outer joins. Therefore, my idea here will not work at all. Thanks to #Elbek for the answer -- it led me to this revelation.
You can use JPA callback methods.
public class Person {
#Id
#Column(name = "PERSON_ID")
private Long personId;
#Transient
private transient Boolean superAdmin = false;
// This method will be called automatically when object is loaded
#PostLoad
void onPostLoad() {
// BTW, personId has to be present in the table since it is id column. Do you want to check if it is 1?
superAdmin = personId == 1;
}
}
or you can create easy getter method.
public class Person {
#Id
#Column(name = "PERSON_ID")
private Long personId;
boolean isSuperAdmin() {
return personId == 1;
}
}
You can't have an optional relationship with a #SecondaryTable. You do not have any other choice than using a #OneToOne optional relationship in that case.
I'm quite new to Hibernate and have been trying to determine what it will do for you and what it requires you to do.
A big one is dealing with an object that has dependants that don't yet exist in the database. For example, I have a Project object that includes a Manufacturer field that accepts a Manufacturer object as its value. In the database I have a products table with a mfr_id column that's a reference to the manufacturers table (a fairly typical unidirectional one-to-many relationship).
If the manufacturer assigned to the product object relates to one that's already in the database then there's no problem. However, when I try to save or update an object that references a manufacturer that hasn't been persisted yet, the operation fails with an exception.
Exception in thread "Application" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing
I can of course manually check the state of the product's manufacturer by seeing if it's ID field is null and saving it if it is, but this seems like a cumbersome solution. Does Hibernate support automatically persisting dependants if the dependant in question isn't yet persisted? If so, how do I enable that behaviour? I'm using the version of Hibernate bundled with Netbeans (3.5, I believe) and inline annotations for specifying the mapping behaviour. Below are my product and manufacturer classes, cut down to the parts that handle the dependency. (Product extends Sellable which maps to a sellable table, using JOINED as the inheritance strategy It's that table that contains the primary key that identifies the product)
#Entity
#Table (
name="products",
schema="sellable"
)
public abstract class Product extends Sellable {
private Manufacturer manufacturer;
#ManyToOne (fetch = FetchType.EAGER)
#JoinColumn (name = "mfr_id")
public Manufacturer getManufacturer () {
return this.manufacturer;
}
/**
*
* #param manufacturer
*/
public Product setManufacturer (Manufacturer manufacturer) {
this.manufacturer = manufacturer;
return this;
}
}
The dependant Manufacturer
#Entity
#Table (
name="manufacturers",
schema="sellable",
uniqueConstraints = #UniqueConstraint(columnNames="mfr_name")
)
public class Manufacturer implements Serializable {
private Integer mfrId = null;
private String mfrName = null;
#Id
#SequenceGenerator (name = "manufacturers_mfr_id_seq", sequenceName = "sellable.manufacturers_mfr_id_seq", allocationSize = 1)
#GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "manufacturers_mfr_id_seq")
#Column (name="mfr_id", unique=true, nullable=false)
public Integer getMfrId () {
return mfrId;
}
private Manufacturer setMfrId (Integer mfrId) {
this.mfrId = mfrId;
return this;
}
#Column(name="mfr_name", unique=true, nullable=false, length=127)
public String getMfrName () {
return mfrName;
}
public Manufacturer setMfrName (String mfrName) {
this.mfrName = mfrName;
return this;
}
}
UPDATE: I tried the following from this question, but I still get the transient object exception.
#ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
I also checked what version of Hibernate is bundled with Netbeans, it's 3.2.5
UPDATE 2: I found that the following appears to apparently work as I wanted.
#ManyToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
However, I suspect that this is not the cascade type I really want. If I delete a product, I don't think deleting its associated manufacturer is the correct action, which is what I believe will happen now.
I did try creating a cascade type that consisted of all the types that were available, but that didn't work either. I got the same exception when I tried to save a product that had an unsaved manufacturer associated with it.
#ManyToOne (fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
I've seen CascadeType.SAVE_UPDATE mentioned in several places, but that mode doesn't seem to be available in the version of Hibernate that comes with Netbeans.
You have to look at cascading operations; this type of operation permits you to manage lifecycle of inner object respect their parent.
#ManyToOne(cascade) if you use Session.persist() operation or org.hibernate.annotations.#Cascade if you use not JPA function Session.saveOrUpdate().
This is just an example, for full doc point here
For your code, if you want to automatically save Manufacturer when saving Project use:
#ManyToOne (fetch = FetchType.EAGER, cascade = {javax.persistence.CascadeType.PERSIST})
#JoinColumn (name = "mfr_id")
public Manufacturer getManufacturer () {
return this.manufacturer;
}
or
#Cascade(CascadeType.PERSIST)
Can anyone tell me whether Hibernate supports associations as the pkey of an entity? I thought that this would be supported but I am having a lot of trouble getting any kind of mapping that represents this to work. In particular, with the straight mapping below:
#Entity
public class EntityBar
{
#Id
#OneToOne(optional = false, mappedBy = "bar")
EntityFoo foo
// other stuff
}
I get an org.hibernate.MappingException: "Could not determine type for: EntityFoo, at table: ENTITY_BAR, for columns: [org.hibernate.mapping.Column(foo)]"
Diving into the code it seems the ID is always considered a Value type; i.e. "anything that is persisted by value, instead of by reference. It is essentially a Hibernate Type, together with zero or more columns." I could make my EntityFoo a value type by declaring it serializable, but I wouldn't expect this would lead to the right outcome either.
I would have thought that Hibernate would consider the type of the column to be integer (or whatever the actual type of the parent's ID is), just like it would with a normal one-to-one link, but this doesn't appear to kick in when I also declare it an ID. Am I going beyond what is possible by trying to combine #OneToOne with #Id? And if so, how could one model this relationship sensibly?
If the goal is to have a shared primary key, what about this (inspired by the sample of Java Persistence With Hibernate and tested on a pet database):
#Entity
public class User {
#Id
#GeneratedValue
private Long id;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Address shippingAddress;
//...
}
This is the "parent" class that get inserted first and gets a generated id. The Address looks like this:
#Entity
public class Address implements Serializable {
#Id #GeneratedValue(generator = "myForeignGenerator")
#org.hibernate.annotations.GenericGenerator(
name = "myForeignGenerator",
strategy = "foreign",
parameters = #Parameter(name = "property", value = "user")
)
#Column(name = "ADDRESS_ID")
private Long id;
#OneToOne(mappedBy="shippingAddress")
#PrimaryKeyJoinColumn
User user;
//...
}
With the above entities, the following seems to behave as expected:
User newUser = new User();
Address shippingAddress = new Address();
newUser.setShippingAddress(shippingAddress);
shippingAddress.setUser(newUser); // Bidirectional
session.save(newUser);
When an Address is saved, the primary key value that gets inserted is the same as the primary key value of the User instance referenced by the user property.
Loading a User or an Address also just works.
Let me know if I missed something.
PS: To strictly answer the question, according to Primary Keys through OneToOne Relationships:
JPA 1.0 does not allow #Id on a OneToOne or ManyToOne, but JPA 2.0 does.
But, the JPA 1.0 compliant version of Hibernate
allows the #Id annotation to be used on a OneToOne or ManyToOne mapping*.
I couldn't get this to work with Hibernate EM 3.4 though (it worked with Hibernate EM 3.5.1, i.e. the JPA 2.0 implementation). Maybe I did something wrong.
Anyway, using a shared primary key seems to provide a valid solution.
Yes that is possible.
Look at the following example using Driver and DriverId class as id for Driver.
#Entity
public class Drivers {
private DriversId id; //The ID which is located in another class
public Drivers() {
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "personId", column = #Column(name = "person_id", nullable = false))})
#NotNull
public DriversId getId() {
return this.id;
}
//rest of class
}
Here we are using personId as the id for Driver
And the DriversId class:
//composite-id class must implement Serializable
#Embeddable
public class DriversId implements java.io.Serializable {
private static final long serialVersionUID = 462977040679573718L;
private int personId;
public DriversId() {
}
public DriversId(int personId) {
this.personId = personId;
}
#Column(name = "person_id", nullable = false)
public int getPersonId() {
return this.personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof DriversId))
return false;
DriversId castOther = (DriversId) other;
return (this.getPersonId() == castOther.getPersonId());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getPersonId();
return result;
}
}
You can do this by sharing a primary key between EntityFoo and EntityBar:
#Entity
public class EntityBar
{
#Id #OneToOne
#JoinColumn(name = "foo_id")
EntityFoo foo;
// other stuff
}
#Entity
public class EntityFoo
{
#Id #GeneratedValue
Integer id;
// other stuff
}
You have to use #EmbeddedId instead of #Id here.
And EntityFoo should be Embeddable.
Another way is to put an integer, and a OneToOne with updateble and instertable set to false.