1. 程式人生 > >Hibernate使用JPA註解宣告一個PO類

Hibernate使用JPA註解宣告一個PO類

第一步:在hibernate.cfg.xml配置資料庫連線和連線池


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory
>
<!-- 配置連線資料庫 --> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url"
>
jdbc:mysql:///hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property> <!-- 配置方言是非常重要!!!我這裡配置的為MySQL5Dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 配置C3P0連線池 --> <property name="hibernate.c3p0.max_size"
>
200</property> <property name="hibernate.c3p0.min_size">2</property> <property name="hibernate.c3p0.max_statements">50</property> <property name="hibernate.c3p0.timeout"></property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 配置對映檔案 --> <mapping class="cn.codekong.entity.Students"/> </session-factory> </hibernate-configuration>

第二步編寫持久化類

package cn.codekong.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_StuInfo")
public class Students{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int sid;
    private String sname;
    private String gender;
    private String address;

    public Students() {

    }



    public Students(int sid, String sname, String gender, String address) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.address = address;
    }



    public int getSid() {
        return sid;
    }



    public void setSid(int sid) {
        this.sid = sid;
    }



    public String getSname() {
        return sname;
    }



    public void setSname(String sname) {
        this.sname = sname;
    }



    public String getGender() {
        return gender;
    }



    public void setGender(String gender) {
        this.gender = gender;
    }



    public String getAddress() {
        return address;
    }



    public void setAddress(String address) {
        this.address = address;
    }



    @Override
    public String toString() {
        return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", address=" + address + "]";
    }
}

第三步測試

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import cn.codekong.entity.Students;

public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {
        // 建立服務註冊物件
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        // 建立會話工廠物件
        sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        // 會話物件
        session = sessionFactory.openSession();
        // 開啟事物
        transaction = session.beginTransaction();
    }

    @After
    public void destory() {
        // 提交事物
        transaction.commit();
        // 關閉會話
        session.close();
        // 關閉會話工廠
        sessionFactory.close();
    }

    @Test
    // 向資料庫中新增資料
    public void testSaveStudents() { // 生成學生物件
        Students student = new Students(1, "小麗", "女", "成都");
        System.out.println(student);
        session.save(student);
        System.out.println(session);
    }



}

結果:

Hibernate: 

    create table t_StuInfo (
       sid integer not null auto_increment,
        address varchar(255),
        gender varchar(255),
        sname varchar(255),
        primary key (sid)
    ) engine=MyISAM
Students [sid=1, sname=小麗, gender=女, address=成都]
Hibernate: 
    insert 
    into
        t_StuInfo
        (address, gender, sname) 
    values
        (?, ?, ?)
SessionImpl(PersistenceContext[entityKeys=
[EntityKey[cn.codekong.entity.Students#1]],
collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} 
updates=ExecutableList{size=0} 
deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} 
collectionCreations=ExecutableList{size=0}
collectionRemovals=ExecutableList{size=0}
collectionQueuedOps=ExecutableList{size=0}
unresolvedInsertDependencies=null])