• hibernate基本配置


    将讲解表名类名不一致、属性名列名不一致、不持久化某属性、Date类型的注解、枚举类型的注解(枚举类型在xml配置有点麻烦不说了),说明都在代码注释里。

    项目目录:

    注解方式以Teacher类为例,xml方式以Student类为例:

    Teacher代码:

    package com.oracle.hibernate.model;
    
    import java.util.Date;
    
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.persistence.Transient;
    
    @Entity
    @Table(name="_Teacher")//指定表名
    public class Teacher {
    
        
        private int id;
        private String name;
        private String wifeName;
        private Date birthDate;
        //Title是Enum(枚举)类型
        private Title  title;
        
        @Id
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        //属性默认都是basic,可以不写.
        @Basic
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        //不持久化该属性,Transient,透明的。在数据库里讲没有该字段。
        @Transient
        public String getWifeName() {
            return wifeName;
        }
        public void setWifeName(String wifeName) {
            this.wifeName = wifeName;
        }
        /**
         * 属性名和数据库字段名不一致时,用该注解指定
         * Temporal()一般默认就行
         * value:
         * TemporalType.DATE  只保存日期
         * TemporalType.TIME  只保存时间  
         * TemporalType.TIMESTAMP(默认值,保存日期和时间)
         * @return
         */
        @Column(name="T_BirtyDate")
        @Temporal(TemporalType.TIMESTAMP)
        public Date getBirthDate() {
            return birthDate;
        }
        public void setBirthDate(Date birthDate) {
            this.birthDate = birthDate;
        }
        
        /**
         * 枚举类型@Enumerated(EnumType.ORDINAL/EnumType.STRING)
         * EnumType.ORDINAL:默认值,把枚举类型的数组下标值存入数据库。如A为0,B为1,C为2。此时表字段类型为int
         * EnumType.STRING:把枚举类型的值存进数据库,此时需要把表的字段类型改为varchar。
         * @return
         */
        @Enumerated(EnumType.STRING)
        public Title getTitle() {
            return title;
        }
        public void setTitle(Title title) {
            this.title = title;
        }
        
        
    }

    Student类代码:

    package com.oracle.hibernate.model;
    
    import java.sql.Date;
    
    public class Student {
        private int id;
        private String name;
        private int age;
        private String addr;
        private Date birthDay;
        public Date getBirthDay() {
            return birthDay;
        }
        public void setBirthDay(Date birthDay) {
            this.birthDay = birthDay;
        }
        public String getAddr() {
            return addr;
        }
        public void setAddr(String addr) {
            this.addr = addr;
        }
        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 int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            
            return "ID:"+id+"	"+"name:"+name+"	"+"age:"+age;
        }
        
    }

    教室类用到的枚举类Title:

    package com.oracle.hibernate.model;
    
    public enum Title {
        A,B,C
    }

    Student类需要的Student.hbm.xml配置:

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <!-- 映射的是哪个package里的类 -->
    <hibernate-mapping package="com.oracle.hibernate.model">
    <!-- 类到表的映射 类名若和表名一致,table可以省略-->
    <!--  在oracle里没有自动递增,需要用序列定义id自动递增
    <id name="personId"  column="P_ID">
                <generator class="native">
                    <param name="sequence">SEQ_HIBERNATE(序列名)</param>
                </generator>
            </id>
    -->
        <class name="Student" table="_Student">
            <id name="id" column="id"></id>
            
            <!-- property里的类型type="",95%情况不用指定,hibernate会自动帮你指定 -->
            
            <property name="name" type="string" column="S_Name"></property>
            <property name="age" column="S_Age"></property>
            <property name="birthDay" column="S_BirthDay"></property>
            
            <!-- 不想持久化的属性,直接不写就行 -->
            <!-- <property name="addr"></property> -->
        </class>
    
    </hibernate-mapping>

    Teacher测试类TeacherTest:用的Junit测试

    package com.oracle.hibernate.model;
    
    import java.util.Date;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    public class TeacherTest {
    
        //SessionFactory就像Connection,建立耗时,这里用单例。不管有多少测试方法,都用这一个SessionFactory
        private static SessionFactory sf = null;
        //@BeforeClass,对象初始化之前,classload到内存之后马上执行的方法。
        @BeforeClass
        public static void beforeClass(){
            //用的是注解,new的是AnnotationConfiguration()
            sf = new AnnotationConfiguration().configure().buildSessionFactory();
            
        }
        
        
        @Test 
        public void test() {
            Teacher  t = new  Teacher();
            //id设成了自动递增
            //t.setId(3);
            t.setName("t2");
            t.setBirthDate(new Date());
            
            t.setTitle(Title.B);
        
            Session  session = sf.openSession();
            session.beginTransaction();
            session.save(t);
            session.getTransaction().commit();
            session.close();
            
        }
        
        //类用完之后
        @AfterClass
        public static void afterClass(){
            
            sf.close();
        }
    
    }

    Student测试类StudentTest:

    package com.oracle.hibernate.model;
    
    import static org.junit.Assert.*;
    
    import java.util.Date;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    public class StudentTest {
    
    
        private static SessionFactory sf = null;
        
        @BeforeClass
        public static void beforeClass(){
            //用的是注解,new的是AnnotationConfiguration()
            sf = new AnnotationConfiguration().configure().buildSessionFactory();
            
        }
        
        
        @Test 
        public void test() {
            Student  s = new  Student();
            //在mysql里定义了id为自动递增。不用set。
            //s.setId(1);
            s.setName("s1");
            s.setAge(10);
            //s.setAddr("addr");
            
            
            Session  session = sf.openSession();
            session.beginTransaction();
            session.save(s);
            session.getTransaction().commit();
            session.close();
            
        }
        
        //类用完之后
        @AfterClass
        public static void afterClass(){
            
            sf.close();
        }
    
    }

    在mysql里指定_student表和_teacher表的id为自动递增。

    运行几次,效果如下:

    _teacher表:

    可以看到,字段名改了,wifeName字段为也没生成。存进去的时间为date类型。

    若把注解的枚举类型的改为EnumType.ORDINAL,则title存进去的是0、1、2。

    _student表:

  • 相关阅读:
    Rational全系列工具介绍
    转贴 MM(ModelMaker)建模工具快速上手指南delphi
    eclipse打不开报(Failed to create the Java Virtual Machine)解决方法
    Vagrant系列(二)Vagrant的配置文件Vagrantfile详解
    Xshell登录Vagrant方式
    win10系统在执行“ vagrant box add centos7 vagrantcentos7.box”添加box时,报错“Vagrant failed to initialize at a...
    win10系统搭建vagrant时开启bios,虚拟化问题
    查看memcache版本
    python空为None
    python 获得字符串长度
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/4848914.html
Copyright © 2020-2023  润新知