I want to implement OneToOne annotations on a class. I downloaded the jar containing JPA Data code but i know it doesn't work that way. What else do i need to do to make it work?
CodePudding user response:
If you use Maven then you should choose a JPA implementation, usually its Hibernate and add it to your dependencies.
e.g.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>jpa-hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.21.Final</version>
</dependency>
</dependencies>
</project>
Hibernate brings along JPA api (persistence-api) and you can annotate your entity classes as per it's annotations.
E.g. with the above pom.xml file you can create some Entities
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
}
and
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@OneToOne(mappedBy = "address")
private User user;
}
and use the annotations accordingly. However please note that @OneToOne
annotation should be used on a @Entity
class, you can't just put it in a class that is not annotated @Entity
.
What's is not shown here is the configuration of Hibernate, usually it is done in xml with a file called persistence.xml
placed into src\main\resources\META-INF
directory.
CodePudding user response:
You need a Java server and a relational database. I suggest Apache TomEE (server) and HSQLDB (in-memory relational database).
Here's an example: https://tomee.apache.org/latest/examples/jpa-hibernate.html