SpringData JPA multi-table operation (add, delete)

Many:

  Examples: customer relations and contacts

  In the entity class, because the customer is one of the few, it should contain more than one contact, so the entity class to reflect the customers have more than one contact information

/**
 * Customer entity class
 */
@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_source")
    private String custSource;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone ")
    private String custPhone;

    // @OneToMany(targetEntity = LinkMan.class, fetch = FetchType.LAZY)
    // @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    /**
     * Give up the right to maintain a foreign key
     * MappedBy: other configuration properties Name of relationship
     * Cascade: cascade configuration (can be configured into a multi-table mapping between the notes)
     * CascadeType.all: All
     * MERGE: update
     * PERSIST: save
     * REMOVE: Delete
     * Fetch: Configuration loading associated objects
     * EAGER: load immediately
     * LAZY: delay loading
     */
    @OneToMany(mappedBy = "customer")
    private Set<LinkMan> linkMans = new HashSet<>(0);

    / ** ********************** GET / the SET method ********************* ** * / 
}

  Since the contact is more than one, the entity class should reflect each contact corresponds to only one client

/**
 * Contact entity class
 */
@Entity
@Table(name = "cst_linkman")
public class LinkMan {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "lkm_id")
    private Long lkmId;
    @Column(name = "lkm_name")
    private String lkmName;
    @Column(name = "lkm_gender")
    private String lkmGender;
    @Column(name = "lkm_phone")
    private String lkmPhone;
    @Column(name = "lkm_mobile")
    private String lkmMobile;
    @Column(name = "lkm_email")
    private String lkmEmail;
    @Column(name = "lkm_position")
    private String lkmPosition;
    @Column(name = "lkm_memo")
    private String lkmMemo;

    /**
     * Many-to configure contact customer relations
     * Configure many-to-use annotation form of relationship
     * 1 configuration table relationship
     * @ManyToOne: Configure many-relationship
     * TargetEntity: other entity class bytecode
     * Configuration foreign key (many-configuration intermediate table)
     * Foreign key configuration process, the configuration to a multi-party, multi-party will maintain the foreign key
     */
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private Customer customer;

    / ** ********************** GET / the SET method ********************* ** * / 
}

  Persistence Layer Interface

/**
 * Customer persistence layer interface
 * JpaRepository <entity class type, primary key type>: to perform basic CRUD operations
 * JpaSpecificationExecutor <Entity class types>: for complex queries (pagination query)
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
/**
 * Contact persistence layer interface
 */
public interface LinkManDao extends JpaRepository<LinkMan, Long>, JpaSpecificationExecutor<LinkMan> {
}

  Testing new record

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class OneToManyTest {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LinkManDao linkManDao;

    /**
     * Save a client, save a contact
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
        Customer customer = new Customer();
        customer.setCustName ( "Master" );
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("宁缺");

        /**
         * Configured to contact the customer relations
         * From the customer's point: transmitting two insert statement, an update statement sent to update the database (updated foreign key)
         * Since we configured the client to relational contacts: Customers can maintain foreign key
         */
        customer.getLinkMans().add(linkMan);

        /**
         * Configuration of contact to the customer relationship (many to one)
         * Send only the two insert statements
         * Thanks to a contact to the customer mapping relationship (many to one): Contact foreign key can also be maintained
         */
        // linkMan.setCustomer(customer);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }

    / ** *** *** final recommendations of use
     * There will be an extra update statement
     * * As the party can maintain a foreign key: sends an update statement
     * * Resolve this problem: You only need to give up the right to maintain a party to
     *
     */
    @Test
    @Transactional
    @Rollback ( false )
     public  void testAdd2 () {
         // create a customer, create a contact 
        the Customer the Customer = new new the Customer ();
        customer.setCustName ( "Chen" );

        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName ( "Longqing" );

        linkMan.setCustomer (the Customer); // Thanks to a multi-party relationship to a party (when saved, had the foreign key assignments) 
        customer.getLinkMans () the Add (LINKman);. // Thanks to a a party to more than one association (send an update statement)

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }
}

  Test delete records

@Test
@Transactional
@Rollback(false)
public void testDelete() {
    customerDao.delete(1L);
}

  Deletion described as follows:
    Remove the data from the table: can be deleted at any time.
    Remove master table data:
      there are data from Table
        1, in default, it would a foreign key field is set to null, and then delete the master table data. If the structure of the database table, field has a non-null foreign key constraint, default error is reported.
        2, if a waiver of maintaining the correlation between the configuration can not be deleted (and whether to allow the foreign key field is null, it does not matter) because when you delete, it does not go to the foreign key table updates from the field.
        3, if you want to delete, using cascading deletes references (caution)

      No reference data from the table: just delete

Cascaded operation: simultaneous operation refers to an operation that a target associated object

  Usage: cascade arranged only on the operating body annotations

  @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private Set<LinkMan> linkMans = new HashSet<>(0);
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class CascadeTest {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LinkManDao linkManDao;

    /**
     * Cascade added: save a customer at the same time, saving customers all contacts
     * Required operation on the entity class body disposed casacde properties
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testCascadeAdd() {
        Customer customer = new Customer();
        customer.setCustName ( "Baidu" );

        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName ( "Mike" );

        linkMan.setCustomer(customer);
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);
    }
    
    /**
     * Cascading Delete:
     * Remove No. 1 client at the same time, delete all contacts 1 customer
     */
    @Test
    @Transactional
    @Rollback ( false )
     public  void testCascadeRemove () {
         // 1. No. 1 customer query 
        the Customer the Customer = customerDao.findOne (1L );
         // 2. Delete No. 1 customer 
        customerDao.delete (customer);
    }
}

Many to many:

  Example: the relationship between users and roles

  Table-many relationship is established by the middle of the table, where the relationship between the user and the middle of the table is a table-many relationship between the table and the role of the middle of the table is one to many

  Build relationships, and the entity class mapping configuration:

    A user may have multiple roles, the user entity class should contain information of a plurality of roles

/**
 * User entity class
 */
@Entity
@Table(name = "sys_user")
public class SysUser implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;
    @Column(name = "user_code")
    private String userCode;
    @Column(name = "user_name")
    private String userName;
    @Column(name = "user_password")
    private String userPassword;
    @Column(name = "user_state")
    private String userState;
  
/**   * Configure user roles to many relationship   * Configure-many mapping between   * Configuration 1. Declare table relationships   * @ManyToMany (targetEntity = SysRole.class) // many to many   * TargetEntity: on behalf of the other entity class bytecode   * Configuration intermediate table (which contains two foreign keys)   * @Jointble   * Name: the name of the middle of the table   * JoinColumns: current object disposed intermediate the foreign key in the table   * @JoinColumn array   * Name: the name of the foreign key   * ReferencedColumnName: main reference table primary key name   * InverseJoinColumns: other objects disposed intermediate the foreign key in table   */   @ManyToMany(targetEntity = SysRole.class)   @JoinTable (name = "sys_user_role" , // joinColumns, the current object in the middle of the foreign key table joinColumns @JoinColumn = {(name = "sys_user_id", the referencedColumnName = "user_id" )}, // inverseJoinColumns, among other objects foreign key table inverseJoinColumns @JoinColumn = {(name = "sys_role_id", the referencedColumnName = "role_id" )}   )   private Set<SysRole> roles = new HashSet<SysRole>(0);
  
/************************ get/set方法 ************************/
}

    A plurality of users can be given a role, the role of the entity class should contain information of a plurality of users

/**
 * Role entity class
 */
@Entity
@Table(name = "sys_role")
public class SysRole implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "role_id")
    private Long roleId;
    @Column(name = "role_name")
    private String roleName;
    @Column (name = "role_memo" )
     Private String roleMemo; 
  
// many-to-relational mapping   @ManyToMany (the mappedBy = "the Roles") // other configuration properties Name of relationship, the other party is represented by the middle of the table to maintain the relationship between the   Private the Set <SYSUSER > Users = new new HashSet <SYSUSER> (0 );
  
/ ** ************************************************************ GET / SET method ********* ************** * / }

  Persistence Layer Interface:

/**
 * Persistence Layer User Interface
 */
public interface SysUserDao extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {
}
/**
 * The role of persistence layer interfaces
 */
public interface SysRoleDao extends JpaRepository<SysRole, Long>, JpaSpecificationExecutor<SysRole> {
}

  test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class ManyToManyTest {

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysUserDao sysUserDao;

    /**
     * Save a user to save a role
     * Maintenance-many give up the right to: a passive party give up
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
        SysUser sysUser = new SysUser();
        sysUser.setUserName("小强");

        SysRole sysRole = new SysRole();
        sysRole.setRoleName ( "the Java programmer" );

        // configured to user role relationships, the data can maintain the intermediate table 
        sysUser.getRoles () add (sysRole). ;

        // relationship configured to the user's role, can maintain data middle of the table (to give up maintenance) 
        sysRole.getUsers () the Add (SYSUSER).;

        sysUserDao.save(sysUser);
        sysRoleDao.save(sysRole);
    }
}

 

    In many to many (save), if the two-way relations are set, which means both sides maintain middle of the table, will insert data into the middle of the table, two middle of the table and field as the primary key, the primary key duplication, so the error

    Saving failed to solve the problem: only need to give up the right to maintain in the middle of the table can be either recommended in a passive party to give up, configuration is as follows:

      // give up the right to maintain the middle of the table, the primary key to solve the preservation problem of conflict
      @ManyToMany (the mappedBy = "the Roles")
      Private the Set <SYSUSER> the Users = new new HashSet <SYSUSER> (0);

Many-cascade operation:

  And, like many, only you need to configure cascade on the subject of the action notes

@ManyToMany(targetEntity = SysRole.class, cascade = CascadeType.ALL)
  @JoinTable (name = "sys_user_role" ,
         // joinColumns, the current object in the middle of the foreign key table 
        joinColumns @JoinColumn = {(name = "sys_user_id", the referencedColumnName = "user_id" )},
         // inverseJoinColumns, among other objects foreign key table 
        inverseJoinColumns @JoinColumn = {(name = "sys_role_id", the referencedColumnName = "role_id" )}
  )
  private Set<SysRole> roles = new HashSet<SysRole>(0);

  test:

/**
     * Add cascading test (save the associated user role to save a user at the same time)
     */
    @Test
    @Transactional
    @Rollback(false)
    public void testCasCadeAdd() {
        SysUser sysUser = new SysUser();
        sysUser.setUserName("小李");

        SysRole sysRole = new SysRole();
        sysRole.setRoleName ( "the Java programmer" );

        sysUser.getRoles (). add (sysRole);
        sysRole.getUsers().add(sysUser);

        sysUserDao.save(sysUser);
    }

    /**
     * Delete operation
     * When deleting many to many, can not cascade delete two-way configuration
     * Disable
     * If equipped, and if there is the relationship between data references may clear all data
     *
     Delete the associated object id 1 users, delete him: * Case
     */
    @Test
    @Transactional
    @Rollback ( to false )
     public  void testCasCadeRemove () {
         // query the user 1 
        SYSUSER = User sysUserDao.findOne (1L );
         // Delete User No. 1 
        sysUserDao.delete (user);
    }

 

Guess you like

Origin www.cnblogs.com/roadlandscape/p/12378696.html