Hibernate基于【XML】和【注解】——完整实例
Eclipse中新建Java Project工程:
工程结构 和 需要的Jar包:

我用的SqlServer数据库,所以连接数据库的Jar包是sqljdbc4.jar
一、基于XML配置
1、实体类(对应数据表中的字段)
package Entity; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
public class Student {
private int id;
private String name;
private int age; public Student(){} public Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} 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;
} }
2、Student.hbm.xml(XML文件 将实体类 对应 数据表 和 表中字段)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>
<class name="Entity.Student" table="Student">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
3、hibernate.cfg.xml(配置连接数据库、映射Student.hbm.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> <!-- Database connection settings 数据库连接配置-->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;database=test</property>
<property name="connection.username">sa</property>
<property name="connection.password">Zhutou0216</property> <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property> <!-- SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <!-- Echo all executed SQL to stdout 在控制台打印后台sql语句-->
<property name="show_sql">true</property>
<!-- 格式化语句 -->
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <!-- 映射数据库对应实体类: xml配置文件生效方式 -->
<mapping resource="entity/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
4、MainApp(运行类)
package Entity; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class MainApp { public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory(); Session session = null;
try{
session = factory.openSession(); session.beginTransaction(); Student student = new Student();
student.setName("en");
student.setAge(88);
session.save(student);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
if(session != null){
if(session.isOpen()){
//关闭session
session.close();
}
}
} } }
二、基于注解配置
1、实体类(在实体类中用注解方式对应数据表和表中字段,因此用不着Student.hbm.xml了)
package Entity; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="Student")
public class Student { @Id @GeneratedValue
@Column(name="id")
private int id; @Column(name="name")
private String name; @Column(name="age")
private int age; public Student(){} public Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} 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;
} }
2、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> <!-- Database connection settings 数据库连接配置-->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;database=test</property>
<property name="connection.username">sa</property>
<property name="connection.password">Zhutou0216</property> <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property> <!-- SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <!-- Echo all executed SQL to stdout 在控制台打印后台sql语句-->
<property name="show_sql">true</property>
<!-- 格式化语句 -->
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <!-- 映射数据库对应实体类: xml配置文件生效方式 -->
<!-- <mapping resource="entity/Student.hbm.xml" /> --> <!-- 映射数据库对应实体类:注解生效方式生效方式 -->
<mapping class="Entity.Student"/> </session-factory> </hibernate-configuration>
3、MainApp(这里没有改变)
package Entity; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class MainApp { public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory(); Session session = null;
try{
session = factory.openSession(); session.beginTransaction(); Student student = new Student();
student.setName("en");
student.setAge(88);
session.save(student);
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally{
if(session != null){
if(session.isOpen()){
//关闭session
session.close();
}
}
} } }
Hibernate基于【XML】和【注解】——完整实例的更多相关文章
- mybatis学习一:基于xml与注解配置入门实例与问题
注:本case参考自:http://www.cnblogs.com/ysocean/p/7277545.html 一:Mybatis的介绍: MyBatis 本是apache的一个开源项目iBatis ...
- MyBatis 项目开发中是基于 XML 还是注解?
只要你对 MyBatis 有所认识和了解,想必知道 MyBatis 有两种 SQL 语句映射模式,一种是基于注解,一种是基于XML. 基于 XML <mapper namespace=" ...
- spring 基于XML和注解的两种事务配置方式
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现
项目结构 基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程) 开始体验 1.新建项目,新建类MybatisUtil.java,路径:src/util/Mybatis ...
- spring的AspectJ基于XML和注解(前置、后置、环绕、抛出异常、最终通知)
1.概念 (1)AspectJ是一个基于Java语言的AOP框架 (2)Spring2.0以后新增了对AspectJ切入点表达式的支持 (3)AspectJ是AspectJ1.5的新增功能,通过JDK ...
- mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)
下面示例在mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现 Demo的基础上进行优化 以新增一个用户为例子,原UserMapper.xml配置如下: < ...
- JavaWeb中点赞功能的实现及完整实例
实现原理1.功能描述:一个用户对同一文章只能点赞一次,第二次就是取消赞2.建立一个点赞表great,字段有文章ID(aid),点赞用户ID(uid)3.当有用户进行点赞行为时,使用aid和uid搜索点 ...
- hibernate中.hbm.xml和注解方式自动生成数据表的简单实例(由新手小白编写,仅适用新手小白)
绝逼新手小白,so 请大神指点! 如果真的错的太多,错的太离谱,错的误导了其他小伙伴,还望大神请勿喷,大神请担待,大神请高抬贵嘴......谢谢. 好了,正题 刚接触ssh,今天在搞使用.hbm.xm ...
- Hibernate+Oracle注解式完整实例
MyEclipse10,新建Web Project,取名hibernate, jar包 1.Cat.java (实体类) package com.hibernate.bean; import java ...
随机推荐
- User-Defined Table Types 用户自定义表类型
Location 数据库--可编程性--类型--用户定义表类型 select one database--> programmability-->types-->user--defi ...
- 51NOD 1069 Nim游戏
1069 Nim游戏 有N堆石子.A B两个人轮流拿,A先拿.每次只能从一堆中取若干个,可将一堆全取走,但不可不取,拿到最后1颗石子的人获胜.假设A B都非常聪明,拿石子的过程中不会出现失误.给出 ...
- xshell5 Linux 上传下载文件
1,先登录身份验证和文件传输ZMODEM 选择自动激活. 2,rpm -qa | grep lrzsz 利用此命令查看是否安装了lrzsz . 如果没有任何反应则是没有安装 若没有安装 yum ins ...
- 【Coursera】Internet History 小结
前言 终于看完了接近一半课程的 History 的内容. 在这两周的时间里面,了解了互联网的起源,发展,以及现在互联网的情况.听了许多故事,有让人会心一笑的,也有令人感慨万千的.见到了许多令人景仰的科 ...
- 05_Flume_timestamp interceptor实践
1.目标场景 2.Flume Agent配置 # specify agent,source,sink,channel a1.sources = r1 a1.sinks = k1 a1.channels ...
- HDU 2546 饭卡(0-1背包)
http://acm.hdu.edu.cn/showproblem.php?pid=2546 题意: 电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额.如果购买一个商品之前,卡上的剩余金 ...
- C++:几种callable实现方式的性能对比
C++中几种callable实现方式的性能对比 前言 C++中想实现一个callable的对象,通常有四种方式: std::function:最common的方式,一般会配合std::bind使用. ...
- python flask demo
from flask import Flask, jsonify from flask import abort from flask import make_response from flask ...
- testNG 学习笔记 Day 1 使用功能详解
TestSuite处理测试用例有6个规约(否则会被拒绝执行测试) A 测试用例必须是公有类(Public) B 测试用例必须继承与TestCase类 C 测试用例的测试方法必须是公有的( Public ...
- Jmeter 测试API接口 查看接口的幂等问题
背景介绍: 比如一个注册接口,要求填入的手机号与DB中已有的不能重复, 如果手机号码重复,则此次注册失败,不会新增会员数据: 如果不重复,则注册成功(忽略其他因素). 但是用20个并发,同样的请求,请 ...