在很多场景下,我们不需要使用jdbctemplate直接操作sql语句,这时候可以用orm工具来节省数大量的的代码和开发时间。orm工具能够把注意力从容易出错的sql代码转向如何实现应用程序的真正需求。
Spring对ORM框架的支持提供了与这些框架的集成点以及一些附加的服务:
支持集成Spring声明式事务;
透明的异常处理;
线程安全的、轻量级的模板类;
DAO支持类;
资源管理。
Hibernate是在开发者社区很流行的开源ORM框架。
mysql新建数据库store,然后执行如下sql:


1 create table Category (2 Id int not null,3 Name varchar(80) null,4 constraint pk_category primary key (Id)5 );6 7 INSERT INTO category(id,Name) VALUES (1,'女装');8 INSERT INTO category(id,Name) VALUES (2,'美妆');9 INSERT INTO category(id,Name) VALUES (3,'书籍');
我用的IDE是IdeaIU,通过maven构建项目,通过xml配置spring。完成后的代码结构为:

class Category{
private int cateId;
private String cateName;
//次数省略get,set方法
@Override
public String toString() {
return "id="+cateId+" name="+cateName;
}
}
系统特点:功能简洁实用。目前互联网上最简洁的企业网站建设系统!原创程序代码。非网络一般下载后修改的代码。更安全。速度快!界面模版分离。原创的分离思路,完全不同于其他方式,不一样的简单感受!搜索引擎优化。做了基础的seo优化。对搜索引擎更友好系统功能关于我们:介绍企业介绍类信息,可自由添加多个介绍栏目!资讯中心:公司或行业资讯类内容展示。可自由添加多个资讯内容!产品展示:支持类别设置,可添加产品图片
0
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/tx ">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/store"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:hibernate/hibernate.cfg.xml"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="categoryDao" class="CategoryDao">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
</beans>
dataSource没什么特别的,就不在解释了。看下其他几点:
①hibernate sessionFactory:
使用Hibernate所需的主要接口是org.hibernate.Session,Session接口提供了CRUD等最基本的数据访问功能。通过Hibernate的Session接口,应用程序的Repository能够满足所有的持久化需求。而获取Hibernate Session对象的标准方式是借助于Hibernate SessionFactory接口的实现类。
在sessionFactory配置主要设置了两个属性:dataSource设置了数据连接,configLocation设置了hibernate配置文件的路径。
②事务
要是数据库操作支持事务,需要配置<tx:annotation-driven/>和transactionManager。
①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="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="hibernate/Category.hbm.xml"/>
</session-factory>
</hibernate-configuration>
②Category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Category" table="Category">
<id name="cateId" column="id">
<generator class="native"/>
</id>
<property name="cateName" column="name"/>
</class>
</hibernate-mapping>
如果方法要支持事务,需要加注解@Transactional。
public class CategoryDao {
private SessionFactory sessionFactory;
public CategoryDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
@Transactional
public void save(Category category) {
currentSession().save(category);
}
@Transactional
public void update(Category category){
currentSession().update(category);
}
@Transactional
public void delete(int id) {
Query query = currentSession().createSQLQuery("DELETE FROM category WHERE Id=::ID");
query.setInteger("::ID", id);
query.executeUpdate();
}
@Transactional
public int count() {
return getAll().size();
}
@Transactional
public Category getById(int id) {
Criteria criteria=currentSession().createCriteria(Category.class);
criteria.add(Restrictions.eq("id",id));
return (Category) criteria.uniqueResult();
}
@Transactional
public List<Category> getAll() {
return currentSession().createCriteria(Category.class).list();
}
}
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class testCategoryDao {
@Autowired
private CategoryDao categoryDao;
@Test
public void testAdd() {
Category category = new Category();
category.setCateId(4);
category.setCateName("母婴");
categoryDao.save(category);
}
@Test
public void testUpdate() {
Category category = new Category();
category.setCateId(4);
category.setCateName("男装");
categoryDao.update(category);
}
@Test
public void testGetById() {
int id = 4;
Category category = categoryDao.getById(id);
if(category==null){
System.out.println("not exist");
}else {
System.out.println(category.toString());
}
}
@Test
public void testGetAll() {
List<Category> categories = categoryDao.getAll();
for (Category item : categories) {
System.out.println(item);
}
}
@Test
public void testCount() {
int count = categoryDao.count();
System.out.println(count);
}
@Test
public void testDelete() {
int id = 4;
categoryDao.delete(id);
}
}以上就是Hibernate简介与实例介绍的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号