Здесь вы можете использовать следующий пример:
@Entity
@Table(name = "users")
class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_friends")
Set<User> friends;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Set<User> getFriends() {
return friends;
}
public void setFriends(Set<User> friends) {
this.friends = friends;
}
public void addFriend(User u) {
if (this.friends == null) {
this.friends = new HashSet();
}
this.friends.add(u);
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="deneme" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.deneme.User</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://127.0.0.1;databaseName=springbootdb"/>
<property name="javax.persistence.jdbc.user" value="emre"/>
<property name="javax.persistence.jdbc.password" value="asdf_1234"/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.ddl-generation" value="auto"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
main:
public class Main {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "deneme");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
User u = new User();
u.setName("test");
u.setSurname("test");
User uf = new User();
uf.setName("fri");
uf.setSurname("fri");
u.addFriend(uf);
entitymanager.persist(u);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
Генерируемый sql:
Hibernate: insert into users (name, surname) values (?, ?)
Hibernate: insert into users (name, surname) values (?, ?)
Hibernate: insert into user_friends (User_id, friends_id) values (?, ?)
Снимок экрана из базы данных: