Hibernate一对多和多对多

一对多

一对多 单向

@Entity
@Table(name = "cz_user")
public class Users {

    @Column(name = "user_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userId;
    @Column(name = "user_name")
    private String username;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "reg_time")
    private Date regTime;

    
    @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)
   @JoinColumn(name = "user_id")//外键维护
    private List<Address> addressList = new ArrayList<Address>();

    public Users() {
    }
    //这里属性的get方法需要有,set方法不需要,当然你可以加上
@Entity
@Table(name = "cz_address")
public class Address {

    @Column(name = "address_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer addressId;
    @Column(name = "consignee")
    private String consignee;
    @Column(name = "province")
    private Integer province;
    @Column(name = "city")
    private Integer city;
    @Column(name = "district")
    private Integer district;
    @Column(name = "street")
    private String street;
    @Column(name = "zipcode")
    private String zipcode;
    @Column(name = "telphone")
    private String telphone;
    @Column(name = "mobile")
    private String mobile;

    public Address() {
    }
     //这里属性的get方法需要有,set方法不需要,当然你可以加上
/**测试级联保存*/
@Transactional
@Override
    public void test() {
        List<Address> addresses = new ArrayList<Address>();
        Address consignee1 = new Address("consignee12", 12, 12, 12);
        Address consignee2 = new Address("consignee22", 22, 22, 22);
        Address consignee3 = new Address("consignee32", 32, 32, 32);
        Address consignee4 = new Address("consignee42", 42, 42, 42);
        addresses.add(consignee1);
        addresses.add(consignee2);
        addresses.add(consignee3);
        addresses.add(consignee4);
        Users users1 = new Users(null, "username2", "email2", "password2", new Date(), addresses);
        userAddressDao.saveUser(users1);
        if (addresses != null && addresses.size() > 0){
            for (Address address : addresses) {
                userAddressDao.updateAddress(address,users1.getUserId());
            }
        }
    }
public void saveUser(Users users) {
        getCurrentSession().save(users);
    }
@Override
    public void updateAddress(Address address,int user_id) {
        int o = getCurrentSession().createQuery("update "+Address.class.getName()+" set user_id = :user_id where addressId = :addressId")
                .setParameter("user_id",user_id)
                .setParameter("addressId",address.getAddressId())
                .executeUpdate();
        logger.warn("外键成功:" + o);
    }

这种单向一对多的级联保存,只需要保存"一方",保存成功之后,“一方”,"多方"的主键会自动回填,然后再去更新外键。这种单向的一对多情况下,"多方"基本上我们是使用不到的。

一对多 双向

@Entity
@Table(name = "cz_user")
public class Users {

    @Column(name = "user_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userId;
    @Column(name = "user_name")
    private String username;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "reg_time")
    private Date regTime;


    @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "users")
    private List<Address> addressList = new ArrayList<Address>();

    public Users() {
    }
 //这里属性的get方法需要有,set方法不需要,当然你可以加上
@Entity
@Table(name = "cz_address")
public class Address {

    @Column(name = "address_id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer addressId;
    @Column(name = "consignee")
    private String consignee;
    @Column(name = "province")
    private Integer province;
    @Column(name = "city")
    private Integer city;
    @Column(name = "district")
    private Integer district;
    @Column(name = "street")
    private String street;
    @Column(name = "zipcode")
    private String zipcode;
    @Column(name = "telphone")
    private String telphone;
    @Column(name = "mobile")
    private String mobile;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")//外键
    private Users users;
 //这里属性的get方法需要有,set方法不需要,当然你可以加上
@Transactional
 @Override
    public void test() {
        List<Address> addresses = new ArrayList<Address>();
        Address consignee1 = new Address("consignee12", 12, 12, 12);
        Address consignee2 = new Address("consignee22", 22, 22, 22);
        Address consignee3 = new Address("consignee32", 32, 32, 32);
        Address consignee4 = new Address("consignee42", 42, 42, 42);
        addresses.add(consignee1);
        addresses.add(consignee2);
        addresses.add(consignee3);
        addresses.add(consignee4);
        Users users1 = new Users(null, "username2", "email2", "password2", new Date(), addresses);
        userAddressDao.saveUser(users1);
        if (addresses != null && addresses.size() > 0){
            for (Address address : addresses) {
                userAddressDao.updateAddress(address,users1.getUserId());
            }
        }
    }
  @Override
    public void saveUser(Users users) {

        getCurrentSession().save(users);
    }

    @Override
    public void updateAddress(Address address,int user_id) {
        int o = getCurrentSession().createQuery("update "+Address.class.getName()+" set user_id = :user_id where addressId = :addressId")
                .setParameter("user_id",user_id)
                .setParameter("addressId",address.getAddressId())
                .executeUpdate();
        logger.warn("外键成功:" + o);
    }

这种单向一对多的级联保存,只需要保存"一方",保存成功之后,“一方”,"多方"的主键会自动回填,然后再去更新外键。这种双向的一对多情况下,是使用最多的
上面两种情况的执行结果

Hibernate: 
    insert 
    into
        cz_user
        (email, password, reg_time, user_name) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cz_address
        (city, consignee, district, mobile, province, street, telphone, user_id, zipcode) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cz_address
        (city, consignee, district, mobile, province, street, telphone, user_id, zipcode) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cz_address
        (city, consignee, district, mobile, province, street, telphone, user_id, zipcode) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cz_address
        (city, consignee, district, mobile, province, street, telphone, user_id, zipcode) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    update
        cz_address 
    set
        user_id=? 
    where
        address_id=?
2021-11-16 15:07:33,193 WARN [com.xysd.ssh.repository.UserAddressDaoImpl] - 外键成功:1
Hibernate: 
    update
        cz_address 
    set
        user_id=? 
    where
        address_id=?
2021-11-16 15:07:33,221 WARN [com.xysd.ssh.repository.UserAddressDaoImpl] - 外键成功:1
Hibernate: 
    update
        cz_address 
    set
        user_id=? 
    where
        address_id=?
2021-11-16 15:07:33,251 WARN [com.xysd.ssh.repository.UserAddressDaoImpl] - 外键成功:1
Hibernate: 
    update
        cz_address 
    set
        user_id=? 
    where
        address_id=?
2021-11-16 15:07:33,309 WARN [com.xysd.ssh.repository.UserAddressDaoImpl] - 外键成功:1

你可能感兴趣的:(java基础,java,hibernate,java)