Hibernate learning mapping 2

Map primary key

        If the identification attribute of the entity class (mapped to the primary key column) is a basic data type, a basic type packaging class, String, Date, etc., you can simply use @Id to modify the entity attribute. There is no need to specify anything when using the @Id annotation Attribute.
        If you want Hibernate to automatically generate the primary key value for the logical primary key, you should also use @GeneratedValue to modify the entity's identification attribute. When using @GeneratedValue, you can specify it as shown in the figure
Insert picture description here
Insert picture description here
Insert picture description here

import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;

import javax.persistence.metamodel.EntityType;

import java.util.Map;

public class Main {
    
    
    private static final SessionFactory ourSessionFactory;

    static {
    
    
        try {
    
    
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
    
    
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
    
    
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
    
    
        final Session session = getSession();
        try {
    
    
            Transaction tx = session.beginTransaction();
            // 创建消息对象
            News n = new News();
            // 设置消息标题和消息内容
            n.setTitle("疯狂Java联盟成立了");
            n.setContent("疯狂Java联盟成立了,"
                    + "网站地址http://www.crazyit.org");
            // 保存消息
            session.save(n);
            // 提交事务
            tx.commit();

        } finally {
    
    
            session.close();
        }
    }
}
import javax.persistence.*;

@Entity
@Table(name="news_inf")
public class News
{
    
    
    // 消息类的标识属性
    @Id
    // 定义主键生成器
    @TableGenerator(name="newsGen" , table="NEWS_ID_GEN",
            pkColumnName="gen_key", valueColumnName="gen_value",
            pkColumnValue="news_id")
    // 使用GenerationType.TABLE主键生成策略
    @GeneratedValue(strategy=GenerationType.TABLE
            , generator="newsGen")
    private Integer id;
    // 消息标题
    private String title;
    // 消息内容
    private String content;

    // id的setter和getter方法
    public void setId(Integer id)
    {
    
    
        this.id = id;
    }
    public Integer getId()
    {
    
    
        return this.id;
    }

    // title的setter和getter方法
    public void setTitle(String title)
    {
    
    
        this.title = title;
    }
    public String getTitle()
    {
    
    
        return this.title;
    }

    // content的setter和getter方法
    public void setContent(String content)
    {
    
    
        this.content = content;
    }
    public String getContent()
    {
    
    
        return this.content;
    }
}

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--加载数据库驱动-->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123</property>
        <!--指定数据库方言-->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- DB schema will be updated if needed -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--在控制台显示SQL语句-->
        <property name="show_sql">true</property>
        <!--将SQL脚本中语句格式化在输出-->
        <property name="hibernate.format_sql">true</property>
        <!--罗列所有的持久化类-->
        <mapping class="News"/>
    </session-factory>
</hibernate-configuration>

Insert picture description here

Map collection properties

        Hibernate requires that the persistent collection value field must be declared as an interface. The actual interface can be java.util.Set, java.util.Collection java.util.List, java. util.Map, java. util. SortedSet, java.util. SortedMap, etc., or even custom types (only need to implement the org. hi bemate. usertype. U serCo llecti on Type interface). The
        reason why Hibernate Hibernate requires the collection interface to declare collection properties is because when the program persists a certain At the time of the instance, Hibernate will automatically replace the collection implementation class in the program with Hibernate's own collection implementation class. Therefore, do not try to force the Hibernate collection properties to be converted to the collection implementation class, such as Hash Set, HashMap, etc., but can be converted to Set, Map and other collections, because Hibernate's own collection class also implements Map, Set and other interfaces.
Insert picture description here
        Regardless of the type of collection properties, they are unified using the @E lementCo llection annotation for mapping. When using the @ElementCollection annotation, you can specify as shown in the figure. Attributes.
Insert picture description here

  • Hibernate uses the standard @CollectionTable annotation mapping to save the table of collection attributes
    Insert picture description here
  • @Join Column annotation is specifically used to define external links
    Insert picture description here

Ordered set mapping

SortedSet

hibernate.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2b8</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>

         <property name="connection.username">root</property>
         <property name="connection.password">123</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- DB schema will be updated if needed -->
       <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <mapping class="Person"/>
    </session-factory>
</hibernate-configuration>
Person.java
import java.util.*;
import javax.persistence.*;
import org.hibernate.annotations.SortNatural;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Entity
@Table(name="person_inf")
public class Person
{
    
    
    @Id @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    // 标识属性
    private Integer id;
    private String name;
    private int age;
    // 有序集合属性
    @ElementCollection(targetClass=String.class)
    // 映射保存集合元素的表
    @CollectionTable(name="training_inf",
            joinColumns=@JoinColumn(name="person_id" , nullable=false))
    // 定义保存集合元素的数据列
    @Column(name="training_name" , nullable=false)
    // 使用@SortNatural指定使用自然排序
    @SortNatural
    private SortedSet<String> trainings
            = new TreeSet<>();

    // id的setter和getter方法
    public void setId(Integer id)
    {
    
    
        this.id = id;
    }
    public Integer getId()
    {
    
    
        return this.id;
    }

    // name的setter和getter方法
    public void setName(String name)
    {
    
    
        this.name = name;
    }
    public String getName()
    {
    
    
        return this.name;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
    
    
        this.age = age;
    }
    public int getAge()
    {
    
    
        return this.age;
    }

    // trainings的setter和getter方法
    public void setTrainings(SortedSet<String> trainings)
    {
    
    
        this.trainings = trainings;
    }
    public SortedSet<String> getTrainings()
    {
    
    
        return this.trainings;
    }
}
Main.java
import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;

import javax.persistence.metamodel.EntityType;

import java.util.Map;

public class Main {
    
    
    private static final SessionFactory ourSessionFactory;

    static {
    
    
        try {
    
    
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
    
    
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
    
    
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
    
    
        final Session session = getSession();
        try {
    
    
            Transaction tx = session.beginTransaction();
            // 创建Person对象
            Person wawa = new Person();
            wawa.setAge(21);
            wawa.setName("crazyit.org");
            // 为trainings集合属性添加2个元素
            wawa.getTrainings().add("Wild Java Camp");
            wawa.getTrainings().add("Sun SCJP");
            session.save(wawa);
            Person p = (Person)session.get(Person.class , 1);
            // 再次添加一个集合元素
            p.getTrainings().add("CCNP");
            tx.commit();
            }
        finally {
    
    
            session.close();
        }
    }
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41827511/article/details/105112762