To-many relationship between the table of 23

There are three multi-database relationships between tables.

Three kinds of entity-relationship system design are: many-to-many and one to one relationship. Note: many relationship can be seen as two: the one to many, many to one. So I speak four more precise.

The basic steps are as follows:

The first step: First, determine the relationship between the two tables. 
 Step two: two realized in the database table relations 
 third step: describe the relationship between two entities in the entity class 
 Step Four: Configure a relationship mapping entity classes and database tables (focus)

Analysis of ideas:

Table relationships established 
in many relationship, we used to call it a party to the main table, the multi-party call from the table. To-many relationship in the database, you need to use a foreign key constraint database. 

What is a foreign key 
refers is one, with reference to the primary key value of the primary table, the column is a foreign key from the table. 

Scene analysis 
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

/ ** 
 * Customer entity class 
 * Annotations are explicitly used the JPA specification 
 * So under the lead pack must be imported javax.persistence package 
 * / 
@Entity // represents the current class is an entity class 
@Table (name = " Customer ") // establishing a correspondence between the entity classes and tables 
@Data
 public  class the Customer the implements the Serializable { 
    
    @Id // indicates that the current master key is a private property 
    @GeneratedValue (strategy = GenerationType.IDENTITY) // generates policy specified primary key 
    the @Column (name = "cid") // specify the database tables and columns correspond cid 
    Private Long CID; 
    the @Column (name = "cname") // the specified database table and column cname corresponding 
    Private String cName;
    The @Column (name  = "source")// the specified source and the corresponding column in the database table 
    Private String source; 
    the @Column (name = "industry") // Specify the database tables and columns correspond to industry 
    Private String industry; 
    the @Column (name = "Level ") // specified level, and the database table columns correspond 
    Private String level; 
    the @Column (name =" address ") // the specified database table and column address corresponding to 
    Private String address; 
    the @Column (name =" Phone ") // specify phone and a corresponding column in a database table 
    Private String phone; 
    
    // configure-many relationship accounts and contacts 
    @OneToMany (= the targetEntity LINKman. class ) 
    @JoinColumn (name="cust_id",referencedColumnName="cust_id")
    private Set<LinkMan> linkmans = new HashSet<LinkMan>(0);
}

Contact entity class

/**
 * 联系人的实体类(数据模型)
 */
@Entity
@Table(name="linkman")
@Data
public class LinkMan implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="lid")
    private Long lId;
    @Column(name="lname")
    private String lName;
    @Column(name="lgender")
    private String lGender;
    @Column(name="lphone")
    private String lPhone;
    The @Column (name= "lmobile" )
     Private String lMobile; 
    @Column (name = "lemail" )
     Private String lEmail; 
    @Column (name = "lposition" )
     Private String lPosition; 
    @Column (name = "lmemo" )
     Private String lMemo; 

    // many to one mapping relation: a plurality of contacts corresponding to the client 
    the @ManyToOne (= the targetEntity the customer. class ) 
    @JoinColumn (name = "the cust_id", the referencedColumnName = "the cust_id" )
     Private the customer customer; // use its primary key, the corresponding contacts the foreign key table 
}

Notes mapping instructions

@OneToMany: 
       action: establish multiple mapping relationship 
    attributes: 
        targetEntityClass: Specifies the number of multi-byte code class of 
        the mappedBy: Specifies the name of the referenced object from the main table entity class table. 
        Cascade: Specifies the cascade operation to use 
        fetch: specifies whether to use delay loading 
        orphanRemoval: whether to delete orphan 

@ManyToOne 
    role: to establish many-relationship 
    attributes: 
        targetEntityClass: a specified one of the entity class bytecode 
        Cascade: you want to use the cascade operation 
        fetch: Specifies whether to use delay loading 
        optional: association is optional. If set to false, it must always exist non-empty relationship. 

@JoinColumn 
     effect: a corresponding relationship between the primary key field and define the foreign key column. 
     Properties: 
        name: Specifies the name of the foreign key fields 
        referencedColumnName: Specifies the name of the primary key field referenced primary table 
        unique: is unique. The default value is not the only 
        nullable: whether to allow empty. The default value allows.
        insertable: whether to allow insertion. The default value allows. 
        updatable: whether to allow updates. The default value allows. 
        columnDefinition: definition information column.

test

@RunWith (the SpringJUnit4ClassRunner. Class ) 
@ContextConfiguration (locations = "CLASSPATH *: * the applicationContext.xml" )
 public  class   OneToManyTest { 
@Autowired 
Private CustomerDao customerDao; 
@Autowired 
Private LinkManDao linkManDao;
       / ** 
       save operation 
       requirements: 
       saving a client and a contact 
       requirements: 
       to create a client object and a contact objects 
       associated relationship (two-way-to-many relationship) between the client and contacts 
     * customer first save and then save contacts 
     * question: 
     * when we build a two-way after the relationship, save the main table, and then save from the table: 
     * will produce two insert and an Update 
     * the actual development, we only need two insert. 
 * / 

@Test
The @Transactional   // open transaction 
@Rollback ( false ) // set to not roll back 
public   void testAdd () { 
the Customer c
= new new the Customer (); c.setCustName ( "Joe Smith" ); c.setCustLevel ( "VIP customers" ); c.setCustSource ( "58 city" ); c.setCustIndustry ( "commercial office" ); c.setCustAddress ( "software Park" ); c.setCustPhone ( "010-10021123" );
LINKman L
= new new LINKman () ; l.setLkmName ( "Zhang" ); L.setLkmGender("Male" ); l.setLkmMobile ( "15,511,111,111" ); l.setLkmEmail ( "[email protected]" ); l.setLkmPosition ( "the chairman" ); l.setLkmMemo ( "amiable" );
c.getLinkMans ( ) .add (L);
l.setCustomer (C); customerDao.save (C); linkManDao.save (L); } }

 By saving the case, we can see that after setting a two-way relationship, will send two insert statements, a redundant update statement, the idea that our solution is very simple, that is a party to give up the right to maintenance

    / ** 
     * give up the right to maintain the foreign key configuration will be changed as follows 
     * / 
// @OneToMany (the targetEntity = LinkMan.class)
 // @JoinColumn (name = "the cust_id", the referencedColumnName = "the cust_id")    
 // set 
    @OneToMany (mappedBy = "customer")

delete

@Autowired
    private CustomerDao customerDao;
    
    @Test
    @Transactional
    @Rollback(false)//设置为不回滚
    public void delete() {
        customerDao.delete(1l);
    }   

Delete operations as follows:

Delete data from the table: can delete at any time. 

Remove master table data: 
 if the 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, with a non-null foreign key field constraint, the default will be given.
  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 a cascade delete references 
does not reference data from the table: just delete 
the actual development, cascading deletes caution! (In many cases)

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

Usage: cascade arranged only on the operating body annotations

  / ** 
     * Cascade: Cascade configuration operations 
     * CascadeType.MERGE Cascade Updates 
     * CascadeType.PERSIST cascade saves: 
     * CascadeType.REFRESH cascade refresh: 
     * CascadeType.REMOVE cascading deletes: 
     * CascadeType.ALL contains all the 
     * / 
    @ the OneToMany (the mappedBy = "Customer", Cascade = CascadeType.ALL in)

 

Guess you like

Origin www.cnblogs.com/zhaochengf/p/12127889.html