Unidirectional many-to-many two-way bi-directional many-to-many individual single one-one-two-way

1 one-way-to-many

1.1 Configuration

Multi-configuration

 //交给jpa管理
@Entity
//创建的表名
@Table(name="t_product")
public class Product {   
    @Id    
    @GeneratedValue   
    private Long id;   
    private String name;
}

1 square configuration

@Entity
@Table(name="t_productDir")
public class ProductDir {
    @Id
    @GeneratedValue
    private Long id;
    private  String name;
    //泛型必须添加进去否则报错必须配置外键id,否则会多生成一张表,形成多对多的关系  
    @OneToMany
    @JoinColumn(name="dir_id")
    private Set<Product> products = new HashSet<>();
 }

1.2 storage

No matter how save, send in additional sql, so the performance is not as many to one
reason is that foreign key is now handled by the party, the party must give extra processing update statement

1.3 Queries

lazy loading

//现在使用 Set集合 HashSet 打印出来 PersistentSet  
//PersistentSet 它是Set的实现类 和 HashSet一样 ,PersistentSet 和 HashSet都是
//Set的实现类,是兄弟关系 --在定义实体的集合的时候,不要定义HashSet
//PersistentBag 也是 List的实现类,和ArrayList一样,ArrayList和PersistentBag都是
//List的实现 ,是兄弟关系 --在定义实体的集合的时候,不要定义ArrayList

to sum up:In the definition of the time when the entity class, if the collection, use the set of interfaces manner

1.4 collection

Now when the defined set, use the List under what circumstances, use the Set under what circumstances?

List / Set difference?

List is an ordered sequence can be repeated Set free, can not be repeated

Set general use in many-to-many

List generally above documents generally used in combination

1.5 Sorting orderby collection

Configuration

@OneToMany
@JoinColumn(name = "dir_id")
@OrderBy("price DESC")       
private List<ProductSet> products = new ArrayList<ProductSet>();  = new HashSet<ProductSet>(); 

2 two-way-to-many or many-to

Configuration: as far as possible to maintain the relationship between the parties, the party waiving management mappedBy

    @OneToMany(mappedBy = "dir")
    private List<Product> products = new ArrayList<>();

Two-way-to-many query Note:

@Test
 // 单项一对多查询就是你查询一方的时候可以 同时可以查询到他对应的多方
            // 若是查询 多方的话就无法查询到一方
        public void testns()throws  Exception{
        /*  若是双向一对多查询  则你查询出来不能直接打印  
        双向多对多是你中有我我中有你的关系  多方里面同时保存了一方的值 
         若是你直接 打印多方或者一方的值 他就会掉用 tostring方法 的同时使懒加载失效
          疯狂重复查询然后报错 所一需要掉用方法来查看值
          System.out.println(student.getDir().getName());

*/
         EntityManager manager = Util.getEntityManager();
            Student student = manager.find(Student.class, 4L);
           
            //String name = student.getName();
            System.out.println(student.getDir().getName());
           // System.out.println(student.getName());



Cascade 2.1 Saving

Cascade: that I operate one of the data, while the data can also multi-operating together

persist(dir);

Cascade is divided into: cascade cascade delete saved

@OneToMany (cascade = CascadeType.PRESIST)

2.2 cascading deletes with caution

@OneToMany(cascade = CascadeType.REMOVE)

2.3 Delete orphans

Let the party to lift the relationship, you can remove from the multi-party 1

cascade = CascadeType.REMOVE  级联删除
mappedBy = "dir"       放弃管理
 orphanRemoval = true   孤儿删除
@OneToMany(cascade = CascadeType.REMOVE,mappedBy = "dir",orphanRemoval = true)

2.4 Strong scene composition used in cascade relationship (document)

Representatives can query and cascade cascading deletes
@OneToMany (cascade = CascadeType.ALL)

3-way-many

3.1-way-many configuration

Many to many

Users and Roles

A user can have multiple roles such as director and actor Hu Ge

A role can have multiple users, such as the role of actor Hu Ge have Eddie Zhao Liying

User-based

@Entity
@Table(name="t_user")
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    // 表示多对多
    @ManyToMany  
               // 中间表的表名                     ueser 的外键
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},
            //反转  user这个表的 反面则是 role
            inverseJoinColumns ={@JoinColumn(name="role_id")} )
    private Set<Role> roles = new HashSet<>();
}

Role

@Entity
@Table(name="t_role")
public class Role {   
    @Id  
   @GeneratedValue    
    private Long id;    
    private String name;
}

3.2 multi-way to save data

Save the code

      //3个用户 2个角色
        User user1 = new User();
        user1.setName("渣渣辉");

        User user2 = new User();
        user2.setName("光头强");

        User user3 = new User();
        user3.setName("王天霸");
        Role role1 = new Role();
        role1.setName("演员");
        Role role2 = new Role();
        role2.setName("导演");

        //设置关系
        user1.getRoles().add(role1);
        user2.getRoles().add(role1);
        user3.getRoles().add(role1);
        user1.getRoles().add(role2);
        user2.getRoles().add(role2);

        //保存数据
        EntityManager entityManager = JpaUtils.getEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(user1);
        entityManager.persist(user2);
        entityManager.persist(user3);
        entityManager.persist(role1);
        entityManager.persist(role2);

        entityManager.getTransaction().commit();

Query: If you are using lazy loading can configure their own lazy

4-many two-way

4.1 Configuration

This party role

@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="role_id")},
            inverseJoinColumns ={@JoinColumn(name="user_id")} )
    private Set<User> users = new HashSet<>();

This user side

 @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},
            inverseJoinColumns ={@JoinColumn(name="role_id")} )
    private Set<Role> roles = new HashSet<>();

4.2 operating

(1) cascade saves:

user configuration cascade save

/*  当你 设置好关系后 直接保存一方 就等于也保存了另外一方(底层实现)
*/
   EntityManager entityManager = JpaUtils.getEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(user1);
        entityManager.persist(user2);
        entityManager.persist(user3);

        entityManager.getTransaction().commit();

(2) delete the configuration of a role does not have strong cascading or cascading deletes

 //保存数据
 EntityManager entityManager = JpaUtils.getEntityManager();
 //查询到一个角色
 User user = entityManager.find(User.class, 1L);
 entityManager.getTransaction().begin();
 // 直接删除这个角色
 entityManager.remove(user);
 entityManager.getTransaction().commit();

(3) Delete all user1 include roles (role1, role2), user1 can not delete this role (only delete the middle of the table)
is not configured or cascade delete cascading strong case

//保存数据
EntityManager entityManager = JpaUtils.getEntityManager();
//查询到一个角色
User user = entityManager.find(User.class, 1L);
entityManager.getTransaction().begin();
// 直接得到这个用户所有的角色 然后清除所有 
user.getRoles().clear();
entityManager.getTransaction().commit();

(4) delete a role user1, user1 can not be deleted (delete only the middle of the table)
is not configured or cascade delete cascading strong case

 //保存数据
 EntityManager entityManager = JpaUtils.getEntityManager();
 // 查询到一个用户
 User user1 = entityManager.find(User.class, 1L);
 // 查询到指定角色信息
 Role role1 = entityManager.find(Role.class, 1L);
 entityManager.getTransaction().begin();
 // 得到这个用户的所有的角色信息  然后删除指定的角色信息
 user1.getRoles().remove(role1);
 entityManager.getTransaction().commit();

(5) delete user roles 3 1 2 3 Adding user roles

 @Test
    public void testDelete4()throws Exception{
        //保存数据
        EntityManager entityManager = JpaUtils.getEntityManager();
        User user3 = entityManager.find(User.class, 3L);
        Role role1 = entityManager.find(Role.class, 1L);
        Role role2 = entityManager.find(Role.class, 2L);
        entityManager.getTransaction().begin();
        user3.getRoles().remove(role1);
        user3.getRoles().add(role2);
        entityManager.getTransaction().commit();
    }

(5) configuration cascade delete cascading deletes party

Configuration

   @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},
            inverseJoinColumns ={@JoinColumn(name="role_id")} )

Code: user3 delete the associated roles delete the associated data deleted middle of the table

 @Test
    public void testDelete5()throws Exception{
        //保存数据
        EntityManager entityManager = JpaUtils.getEntityManager();
        User user3 = entityManager.find(User.class, 3L);
        entityManager.getTransaction().begin();
        entityManager.remove(user3);
        entityManager.getTransaction().commit();

    }

5-one

One-to-many or many-can be seen as a special case

Scene one:

QQ and QQZone

Do not understand the configuration back to the general use of more than 1 instead of one

Key configuration:

(1) do not recommend the use of a unidirectional many-to-many one-way

(2) If you are using more than one pair, try to use two-way configuration, so that a waiver management

(3) To obtain many to many configuration data with each other bidirectional, unidirectional if the one-way operation on the configuration

(4) instead of using many-to-one, if it is a foreign key to use one with a unique way

Published 23 original articles · won praise 2 · Views 939

Guess you like

Origin blog.csdn.net/metjoyful/article/details/101112581