hibernate框架操作持久层数据库:基于Annotation注解实现数据的CRUD

上一篇文章写了基于XML映射文件实现数据的CRUD,这篇文章写基于Annotation注解实现数据的CRUD。

话不多说,直接进入主题!!!!!

<!-- hibernate配置文件 -->

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate配置文件 -->
<hibernate-configuration>
	<session-factory>
	    <!-- Hiberante 连接的基本信息  -->
	    <property name="connection.username">root</property>
	    <property name="connection.password">123456</property>
	    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	    <property name="connection.url">jdbc:mysql:///digital</property>
		
		<!-- Hiberante 方言  -->
		<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
		
		<!-- 是否打印SQL -->
		<property name="show_sql">true</property>		
		
		<!-- 关联 Hibernate 的持久化类 -->
		<mapping class="com.hibernate.entity.UserInfo"/>
	</session-factory>
</hibernate-configuration>

UserInfo类

package com.hibernate.entity;

import java.text.SimpleDateFormat;
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;

//使用@Entity注解,表示当前类为实体Bean,需要进行持久化
@Entity
// 使用@Table注解实现数据表user_info与持久化类UserInfo之间的映射,catalog指定数据库名,name指定表名
@Table(name = "user_info", catalog = "digital")
public class UserInfo {
	private int id;
	private String userName;
	private String password;
	private Date regDate;

	// 使用@Id注解指定当前持久化类的ID标识属性
	@Id
	// 使用@GeneratedValue注解指定主键生成策略为IDENTITY
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	// 使用@Column注解指定当前属性所对应的数据表中的字段,name指定字段名,
	// unique指定是否为唯一,nullable指定是否可为null
	@Column(name = "id", unique = true, nullable = false)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	// 使用@Column注解指定当前属性所对应的数据表的字段,name指定字段名,length指定字段长度
	@Column(name = "userName", length = 16)
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Column(name = "password", length = 16)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "regDate")
	public Date getRegDate() {
		return regDate;
	}

	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}

	/** 无参构造方法 */
	public UserInfo() {
	}

	/** 全部属性的构造方法 */
	public UserInfo(String userName, String password, Date regDate) {
		super();
		this.userName = userName;
		this.password = password;
		this.regDate = regDate;
	}

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", userName=" + userName + ", password="
				+ password + ", regDate="
				+ new SimpleDateFormat("yyyy-MM-dd").format(regDate) + "]";
	}
}

 

hibernateTest类:

package com.hibernate.test;

import static org.junit.jupiter.api.Assertions.*;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.hibernate.entity.UserInfo;


public class hibernateTest {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	@Before
	public void init() {
		// 加载 hibernate.cfg.xml
				final StandardServiceRegistry registry = 
						new StandardServiceRegistryBuilder().configure().build();
				try {
					// 根据 hibernate.cfg.xml 配置 ,初始化 SessionFactory
					sessionFactory = new MetadataSources(registry).buildMetadata()
							.buildSessionFactory();
					// 创建 session
					session = sessionFactory.openSession();
					// 通过session开始事务
					transaction = session.beginTransaction();
				} catch (Exception e) {
					StandardServiceRegistryBuilder.destroy(registry);
				}
	}
	
	/**
	 * 添加数据
	 */
	@Test
	public void testSaveUserInfo() {
		// 初始化UserInfo类
		UserInfo ui = new UserInfo("hibUser1", "123456", new Date());
		// 保存
		session.save(ui);
	}
	
	
	/**
	 * 加载数据
	 * get()
	 * load()
	 */
	@Test
	public void testgetUserInfo() {
		// 初始化UserInfo类
		UserInfo ui = session.get(UserInfo.class,1);
		System.out.printf(ui.toString());
	}
	@Test
	public void testLoadUserInfo() {
		// 初始化UserInfo类
		UserInfo ui = session.load(UserInfo.class,2);
		System.out.printf(ui.toString());
	}
	
	/**
	 * 删除数据
	 */
	@Test
	public void testDeleteUserInfo() {
		UserInfo ui=(UserInfo)session.get(UserInfo.class,9);
		session.delete(ui);
	}
	
	/**
	 * 更新数据
	 */
	@Test
	public void testUpdateUserInfo() {
		UserInfo ui=(UserInfo)session.get(UserInfo.class,10);
		ui.setUserName("CWT");
		//session.update(ui);
		session.saveOrUpdate(ui);
	}
	
	
	@After
	public void destroy() {
		// 提交事务
		transaction.commit();
		// 关闭session
		session.close();
		// 关闭sessionFactory
		sessionFactory.close();
	}
	
}

 

具体java工程,可以到github上面下载压缩包:https://github.com/whitedouble/whitedouble/blob/master/hibernate-2.zip

请各位大神指教。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值