Hibernate基于Annotation配置(二)

来源:互联网 发布:网络男歌手到不了 编辑:程序博客网 时间:2024/05/21 17:54

一:基于入门实例一,通过Annotation配置的方式实现持久化功能

1:在eclipse中新建JAVA PROJECT工程,引入hibernate-release-5.2.2.Final\lib\required下面所有包,还有Oracle驱动包

2:编写Student学生对象类

package com.hibernate.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="STUDENT")public class Student {private String rowId;private String stuCode;private String stuName;@Id@Column(name = "ROW_ID")public String getRowId() {return rowId;}public void setRowId(String rowId) {this.rowId = rowId;}@Column(name = "STU_CODE")public String getStuCode() {return stuCode;}public void setStuCode(String stuCode) {this.stuCode = stuCode;}@Column(name = "STU_NAME")public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}}
3:配置hibernate.cfg.xml文件,参看hibernate-release-5.2.2.Final\project\etc\hibernate.cfg.xml文件进行配置,放在src路径下面。主要Mapping配置的时候从source换成class,直接对应类名

<?xml version='1.0' encoding='utf-8'?>  <!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  <hibernate-configuration>  <session-factory>      <!-- Database connection settings -->      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>      <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>      <property name="connection.username">mzzxzj0913</property>      <property name="connection.password">1</property>      <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>      <property name="show_sql">true</property>      <mapping class="com.hibernate.model.Student" />  </session-factory>  </hibernate-configuration> 
4:编写测试类

package com.hibernate.model;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Test {public static void main(String[] args){Student student = new Student();student.setRowId("00000001");student.setStuCode("1");student.setStuName("xxh");//new Configuration默认读取hibernate.properties,cfg.configure()读取hibernate.cfg.xmlConfiguration cfg = new Configuration();//一个数据库对应一个SessionFactory        SessionFactory sf = cfg.configure().buildSessionFactory();        //一个请求一个Session        Session session = sf.openSession();        //手动开启事务        session.beginTransaction();        session.save(student);        session.getTransaction().commit();        session.close();        sf.close();  }}
5:运行测试类就可以,代码架构和入门实例一一样



0 0
原创粉丝点击