Many to one one one-way association mapping of hibernate in java

Posted by nuying117 on Wed, 23 Oct 2019 18:03:28 +0200

1. I learned crud operation of single table before. In practical applications, most of them are multi table Association operations. This article will learn how to deal with the relationship between multi tables.

2. Investigate the relationship between book list and book classification table. There is a many to one relationship between the book table and the book classification table. The table design of the database is as follows:

3. In java, how to use class relationship to show the relationship between tables

Book.java

public class Book implements Serializable{
    private int id;
    private String name;
    private String author;
    private double price;
    private Date pubDate;
    private Category category;//A reference to one end at the multiple end
   //That is to say, one end of information can be obtained from the other end.
    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 getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Date getPubDate() {
        return pubDate;
    }
    public void setPubDate(Date pubDate) {
        this.pubDate = pubDate;
    }
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
}

Category.java

public class Category implements Serializable{
    private int id;
    private String name;
    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;
    }
}

4. Mapping file relationship

Book.hbm.xml

<hibernate-mapping package="cn.sxt.pojo">
    <class name="Book" table="t_book">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"/>
        <property name="author"/>
        <property name="price"/>
        <property name="pubDate"/>
        <!-- Many to one association settings   column Specify the name of the foreign key -->
        <many-to-one name="category" column="cid"/>
    </class>
</hibernate-mapping>

Category.hbm.xml

<hibernate-mapping package="cn.sxt.pojo">
    <class name="Category" table="t_category">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"/>
    </class>
</hibernate-mapping>

5. test

public class HibernateTest {
    /**
     * Tools and methods for generating database tables
     * */
    @Test
    public void testCreateDB(){
        Configuration cfg = new Configuration().configure();
        SchemaExport se = new SchemaExport(cfg);
        //Print first parameter sql Script
        //The second parameter is whether to export the script to the database for execution.
        se.create(true, true);
    }
    /**
     * Initialize table data
     */
    @Test
    public void testInit(){
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.getSession();
            tx = session.beginTransaction();
            Category c1 = new Category("Computer class");
            Category c2 = new Category("literature");
            Category c3 = new Category("History");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Book b1 = new Book("java","sun",30,df.parse("1995-05-23"));
            b1.setCategory(c1);
            Book b2 = new Book("struts","apache",40,df.parse("2006-09-12"));
            b2.setCategory(c1);
            Book b3 = new Book("What happened in the Ming Dynasty","Bright moon",70,df.parse("2008-05-23"));
            b3.setCategory(c3);
            Book b4 = new Book("Water Margin","Old tearing",20,df.parse("1985-05-23"));
            b4.setCategory(c2);
            session.save(c1);
            session.save(c2);
            session.save(c3);
            session.save(b1);
            session.save(b2);
            session.save(b3);
            session.save(b4);
            tx.commit();
            
        } catch (Exception e) {
            if(tx!=null)
                tx.rollback();
        }finally {
            HibernateUtil.close();
        }
    }
    /**
     * You can get the data on one end when querying the data on the other end
     */
    @Test
    public void testGetData(){
        Session session = HibernateUtil.getSession();
        Book book = (Book)session.get(Book.class, 3);
        System.out.println(book.getId()+"--"+book.getName()+"---"+book.getAuthor()+
                "---"+book.getPrice()+"---"+book.getPubDate()+"---"+book.getCategory().getName());
        
        HibernateUtil.close();
    }
}

Note: when initializing the data, save the order. First save the classification, then save the book.

Topics: PHP Session Java Hibernate Database