---
title: "Hibernate单表操作——单一主键"
author: "cakin24"
date: "2017-11-06T21:46:17Z"
tags: []
categories: ["编程语言"]
slug: "hibernate"
draft: false
lastmod: "2017-11-07T21:23:50Z"
id: 2398842
url: "https://cakin24.iteye.com/blog/2398842"
---

一 单一主键

assigned:由java应用程序负责生成（手工赋值）。

native：由底层数据库自动生成标示符，如果是MySQL，就是increment,如果是Oracle,就是sequence，等等。

 

二 通过native为MySQL生成单一主键

 

1 Students

import java.util.Date;

 

//学生类

public class Students {

        /*

         * JavaBeans的四点原则

         * 1.必须是公有的类

         * 2.提供公有的不带参数的默认的构造方法

         * 3.属性私有

         * 4.属性setter/getter封装

         \*/

        private int sid; // 学号

        private String sname; // 姓名

        private String gender; // 性别

        private Date birthday; // 出生日期

        private String address; // 地址

 

        public Students() {

        }

 

        public Students(int sid, String sname, String gender, Date birthday,

                        String address) {

                // super();

                this.sid = sid;

                this.sname = sname;

                this.gender = gender;

                this.birthday = birthday;

                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 Date getBirthday() {

                return birthday;

        }

 

        public void setBirthday(Date birthday) {

                this.birthday = birthday;

        }

 

        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 + ", birthday=" + birthday + ", address=" + address

                                + "]";

        }

 

}

 

2 StudentsTest

 

import java.util.Date;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.hibernate.service.ServiceRegistry;

import org.hibernate.service.ServiceRegistryBuilder;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

//测试类

public class StudentsTest {

    

    private SessionFactory sessionFactory;

    private Session session;

    private Transaction transaction;

    @Before

    public void init(){

        // 创建配置对象   

        Configuration config = new Configuration().configure();

        //config.addClass(Students.class);

        // 创建服务注册对象

        ServiceRegistry serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();

        // 创建会话工厂对象

        sessionFactory = config.buildSessionFactory(serviceRegistery);

        // 创建会话对象

        session = sessionFactory.openSession();

        // 开启事务

        transaction = session.beginTransaction();

    }

    

    @After

    public void destory(){

        // 提交事务

        transaction.commit();

        // 关闭会话

        session.close();

        // 关闭会话工厂

        sessionFactory.close();

    }

    

    @Test

    public void testSaveStudents(){

        //Students s= new Students(1,"张三丰","男",new Date(),"武当山");

        Students s= new Students();

        s.setSname("张三丰");

        s.setGender("男");

        s.setBirthday(new Date());

        s.setAddress("武当山");

        session.save(s);

    }

}

 

3 Students.hbm.xml

&lt;?xml version="1.0"?&gt;

&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"](http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd%22);&gt;

&lt;!-- Generated 2017-9-17 10:33:28 by Hibernate Tools 3.4.0.CR1 --&gt;

&lt;hibernate-mapping&gt;

    &lt;class name="Students" table="STUDENTS"&gt;

        &lt;id name="sid" type="int"&gt;

            &lt;column name="SID" /&gt;

            &lt;generator class="native" /&gt;

            &lt;!--  &lt;generator class="assigned" /&gt;--&gt;

        &lt;/id&gt;

        &lt;property name="sname" type="java.lang.String"&gt;

            &lt;column name="SNAME" /&gt;

        &lt;/property&gt;

        &lt;property name="gender" type="java.lang.String"&gt;

            &lt;column name="GENDER" /&gt;

        &lt;/property&gt;

        &lt;property name="birthday" type="java.util.Date"&gt;

            &lt;column name="BIRTHDAY" /&gt;

        &lt;/property&gt;

        &lt;property name="address" type="java.lang.String"&gt;

            &lt;column name="ADDRESS" /&gt;

        &lt;/property&gt;

    &lt;/class&gt;

&lt;/hibernate-mapping&gt;

 

4 hibernate.cfg.xml

 

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!DOCTYPE hibernate-configuration PUBLIC

                "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

                "[http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"](http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd%22);&gt;

&lt;hibernate-configuration&gt;

    &lt;session-factory&gt;

        &lt;property name="hibernate.connection.username"&gt;root&lt;/property&gt;

            &lt;property name="hibernate.connection.password"&gt;waDY820828&lt;/property&gt;

            &lt;property name="hibernate.connection.driver\_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;

            &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://127.0.0.1:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-8&lt;/property&gt;

            &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQL5Dialect&lt;/property&gt;

        &lt;property name="show\_sql"&gt;true&lt;/property&gt;

            &lt;property name="format\_sql"&gt;true&lt;/property&gt;

            &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;

            &lt;mapping resource="Students.hbm.xml" /&gt;

    &lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

 

三 测试结果

连续执行两次测试用例

![](http://dl2.iteye.com/upload/attachment/0127/7131/a5ccf3db-3bc5-3770-bd50-b6adecd727d3.png)  
 

![](http://dl2.iteye.com/upload/attachment/0127/7133/d92a39d8-0122-39e4-a771-b4b89660d8a6.png)