欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于Maven的Hibernate入门

程序员文章站 2024-03-23 12:58:10
...

1. Hibernate

Hibernate ORM enables developers to more easily write applications whose data outlives the application process. As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data persistence as it applies to relational databases (via JDBC).

Hibernate框架使开发人员能够轻松的编写java应用程序与数据库交互的开发。 Hibernate是一个开源,轻量级的ORM(对象关系映射)工具。ORM工具简化了数据创建,数据处理和数据访问。它是将对象映射到数据库中存储的数据(表)的编程技术。

更详细的请参考官网:http://hibernate.org/orm/

2. 用Maven实现Hibernate的实例

用maven的理由很简单,省得的每次都下载jar。如果想读源码,也非常非常easy!!!

废话不多说,来个栗子:

1)创建一个maven的project

基于Maven的Hibernate入门

2) 准备好目录结构

基于Maven的Hibernate入门

3)在pom.xml中添加hibernate和oracle的jar的依赖

       <dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
		<!-- Oracle Jdbc Driver -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.2.0</version>
		</dependency>
		<!-- Hibernate 配置 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.1.0.Final</version>
		</dependency>
	</dependencies>

4) 常见实体类com.angelia.hibernate.entity.MyUser

public class MyUser implements java.io.Serializable {

    private int userId;
    private String userName;
    private Date createdDate;

    public MyUser() {
    }

    public MyUser(int userId) {
        this.userId = userId;
    }

	public MyUser(int userId, String userName, Date createdDate) {
		super();
		this.userId = userId;
		this.userName = userName;
		this.createdDate = createdDate;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

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

	public Date getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

	@Override
	public String toString() {
		return "MyUser [userId=" + userId + ", userName=" + userName + ", createdDate=" + createdDate + "]";
	}
}

5) 创建Hibernate映射文件 MyUser.hbm.xml,以类的名字开始MyUser,hbm.xml结尾。

<hibernate-mapping>
	<class name="com.angelia.hibernate.entity.MyUser" table="db_user">
		<id name="userId" type="int">
			<column name="user_id"></column>
			<generator class="assigned"></generator>
		</id>
		<property name="userName" type="string">
			<column name="user_name" length="20"></column>
		</property>

		<property name="createdDate" type="date">
			<column name="created_date" length="7"></column>
		</property>
	</class>
</hibernate-mapping>

6)配置Hibernate描述文件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>
        <property name="connection.username">×××</property>
        <property name="connection.password">×××</property>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@IP:1521:SID</property>
        
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="show_sql">true</property>
        
        <mapping resource="MyUser.hbm.xml" />
    </session-factory>
</hibernate-configuration>

7) 实现HibernateUtil获取SessionFactory

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}

}

8)创建com.angelia.hibernate.dao.MyUserDao

public class MyUserDao {

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    
    public void saveUser(MyUser user){
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        
        session.save(user);
        
        session.getTransaction().commit();
    }
    
    
    public MyUser getUserById(int id){
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        
        List<MyUser> users= session.createQuery("from MyUser where userId = ?").setParameter(0, id).list();
        
        session.getTransaction().commit();
        
        if(users!=null && users.size()>0){
            return users.get(0);
        }
        
        return null;
    }
}

9)创建测试类

public class TestDemo {
	
	@Test
	public void getUserById(){
		
		MyUserDao dao = new MyUserDao();
		
		MyUser user = new MyUser();
		 
                user.setUserId(1);
                user.setUserName("Angelia");
                user.setCreatedDate(new Date());
        
                dao.saveUser(user);
        
                MyUser user2 = dao.getUserById(user.getUserId());
                System.out.println(user2);
	}
}

10)执行测试类

INFO: HHH000262: Table not found: db_user
Hibernate: create table db_user (user_id number(10,0) not null, user_name varchar2(20 char), created_date date, primary key (user_id))
Hibernate: insert into db_user (user_name, created_date, user_id) values (?, ?, ?)
Nov 15, 2017 4:16:06 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Nov 15, 2017 4:16:15 PM org.hibernate.hql.internal.ast.HqlSqlWalker generatePositionalParameter
WARN: [DEPRECATION] Encountered positional parameter near line 1, column 57 in HQL: [from com.angelia.hibernate.entity.MyUser where userId = ?].  Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
Hibernate: select myuser0_.user_id as user_id1_0_, myuser0_.user_name as user_name2_0_, myuser0_.created_date as created_date3_0_ from db_user myuser0_ where myuser0_.user_id=?
MyUser [userId=1, userName=Angelia, createdDate=2017-11-15]Hibernate: create table db_user (user_id number(10,0) not null, user_name varchar2(20 char), created_date date, primary key (user_id))
Hibernate: insert into db_user (user_name, created_date, user_id) values (?, ?, ?)
Nov 15, 2017 4:16:06 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Nov 15, 2017 4:16:15 PM org.hibernate.hql.internal.ast.HqlSqlWalker generatePositionalParameter
WARN: [DEPRECATION] Encountered positional parameter near line 1, column 57 in HQL: [from com.angelia.hibernate.entity.MyUser where userId = ?].  Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
Hibernate: select myuser0_.user_id as user_id1_0_, myuser0_.user_name as user_name2_0_, myuser0_.created_date as created_date3_0_ from db_user myuser0_ where myuser0_.user_id=?
MyUser [userId=1, userName=Angelia, createdDate=2017-11-15]

11)最后的目录结构

基于Maven的Hibernate入门

上一篇: 一道sql面试题

下一篇: