hibernate注解annotation入门了解

前面我们写了实体类之后,都会写一个对应的*.hbm.xml配置文件,然后把这个配置文件关联到hibernate.cfg.xml中,其实hibernate还有另一种写法,来映射对象关系,那就是注解annotation,今天就来简单的先看一下注解怎么使用。


新建一个java项目,项目结构如下:



导入jar包和从官网上获取hibernate压缩包,可以参见《Hibernate环境搭建和配置


新建一个实体类,在实体类中使用注解,代码如下:


package com.ghibernate.pojo;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * entiry表示需要持久化的实体类
 * Table表示实体类所对应的表
 */
@Entity
@Table(name="t_book")
public class Book {

	//Id主键
	@Id
	//指定主键生成策略
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id ;
	@Column(name="book_name")
	private String name ;
	@Column
	private double price ;
	private String author ;
	private Date pubDate ;
	
	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 double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public Date getPubDate() {
		return pubDate;
	}
	public void setPubDate(Date pubDate) {
		this.pubDate = pubDate;
	}
	
	
}

将这个实体类关联到hibernate.cfg.xml中,如:

<!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.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="connection.url">jdbc:mysql:///hibernate4</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<!-- 数据库方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQL5Dialect
	</property>
	<!-- 是否打印sql语句 -->
	<property name="show_sql">true</property>
	<!-- 格式化sql语句 -->
	<property name="format_sql">true</property>
	<!-- 数据库更新方式: 
		1、create:每次更新都先把原有数据库表删除,然后创建该表;
		2、create-drop:使用create-drop时,在显示关闭SessionFacroty时(sessionFactory.close()),将drop掉数据库Schema(表) 
		3、validate:检测;
		4、update(常用):如果表不存在则创建,如果存在就不创建
	-->
	<property name="hbm2ddl.auto">update</property>
	<!-- hbm映射文件 -->
	<mapping class="com.ghibernate.pojo.Book" />

</session-factory>
</hibernate-configuration>

HibernateUtil代码:

package com.robert.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * hibernate工具类
 */
public class HibernateUtil {

	private static Configuration cfg = null;
	private static SessionFactory factory = null;
	private static Session session = null ;
	
	static {
		init();
	}

	/**
	 * 初始化获得Configuration和SessionFacroty对象
	 */
	public static void init() {
		cfg = new Configuration().configure();
		factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
				.applySettings(cfg.getProperties()).build());
	}

	/**
	 * 获得Session对象
	 * @return
	 */
	public static Session getSession() {
		if (factory != null){
			return session = factory.openSession();
		}
		

		init();
		return session = factory.openSession();
	}
	
	/**
	 * 关闭Session
	 */
	public static void closeSession() {
		if(session!=null && session.isOpen())
			session.close();
	}

}

测试类HIbernateTest代码:

package com.ghibernate.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import com.ghibernate.pojo.Book;
import com.robert.util.HibernateUtil;

public class HibernateTest {

	@Test
	public void testCreateDB() {
		Configuration cfg = new Configuration().configure();
		SchemaExport se = new SchemaExport(cfg);
		// 第一个参数:是否生成ddl脚本
		// 第二个参数:是否执行到数据库中
		se.create(true, true);
	}
	
	@Test
	public void testSave() {
		
		Session session = HibernateUtil.getSession() ;
		Transaction tx = session.beginTransaction() ;
		
		Book book = new Book() ;
		book.setName("读者") ;
		book.setPrice(5.6) ;
		book.setAuthor("众人") ;
		book.setPubDate(new Date()) ;
		
		session.save(book) ;
		tx.commit() ;
		HibernateUtil.closeSession();
		
	}

}


使用Junit4运行testCreateDB,生成数据库表

控制台打印的sql语句:

    drop table if exists t_book

    create table t_book (
        id integer not null auto_increment,
        author varchar(255),
        book_name varchar(255),
        price double precision,
        pubDate datetime,
        primary key (id)
    )

运行testSave()方法,存入数据库表中的数据如图:



以上就是annotation的简单用法



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值