30.Spring集成Hibernate不使用hibernate.cfg.xml

 

项目工程目录结构:

依赖jar包:

application-dao.xml文件中的修改,取消引入hibernate.cfg.xml,直接配置hibernate.cfg.xml中的属性

Vo: User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.course.vo;

import java.util.Date;

public class User {

private Integer id;
private String name;
private int age;
private String address;
private Date hireDate;

public User() {
super();
}

public User(String name, int age, String address, Date hireDate) {
super();
this.name = name;
this.age = age;
this.address = address;
this.hireDate = hireDate;
}

public User(Integer id, String name, int age, String address, Date hireDate) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.hireDate = hireDate;
}

public Integer getId() {
return id;
}

public void setId(Integer 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;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Date getHireDate() {
return hireDate;
}

public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", hireDate=" + hireDate
+ "]";
}
}

User.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入xml文件约束 -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.course.vo">

<class name="User" table="User">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<property name="age" column="age"></property>
<property name="address" column="address"></property>
<property name="hireDate" column="hire_date" type="java.util.Date"></property>
</class>
</hibernate-mapping>

Dao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.course.dao;

import java.util.List;

import com.course.vo.User;

public interface UserDao {

public void addUser(User user);
public void updateUser(User user);
public void deleteUser(User user);

public User queryUserById(Integer id);

public List<User> queryAllUser();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.course.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate4.HibernateTemplate;

import com.course.dao.UserDao;
import com.course.vo.User;

public class UserDaoImpl implements UserDao {

// Hibernate-4
private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}

@Override
public void addUser(User user) {
hibernateTemplate.save(user);

}

@Override
public void updateUser(User user) {
hibernateTemplate.update(user);

}

@Override
public void deleteUser(User user) {
hibernateTemplate.delete(user);

}

@Override
public User queryUserById(Integer id) {
User user = hibernateTemplate.get(User.class, id);
return user;
}

@Override
public List<User> queryAllUser() {
List<User> userList = (List<User>) hibernateTemplate.find("from User");
return userList;
}
}

Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.course.service;

import java.util.List;

import com.course.vo.User;

public interface UserService {

public void addUser(User user);
public void updateUser(User user);
public void deleteUser(User user);

public User queryUserById(Integer id);

public List<User> queryAllUser();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.course.service.impl;

import java.util.List;

import com.course.dao.UserDao;
import com.course.service.UserService;
import com.course.vo.User;

public class UserServiceImpl implements UserService {

private UserDao userDao;

public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

@Override
public void addUser(User user) {
userDao.addUser(user);
}

@Override
public void updateUser(User user) {
userDao.updateUser(user);
}

@Override
public void deleteUser(User user) {
userDao.deleteUser(user);
}

@Override
public User queryUserById(Integer id) {
User user = userDao.queryUserById(id);
return user;
}

@Override
public List<User> queryAllUser() {
List<User> userList = userDao.queryAllUser();
return userList;
}
}

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.course.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.course.service.UserService;
import com.course.vo.User;

public class UserController {

private UserService userService;

public void setUserService(UserService userService) {
this.userService = userService;
}

public void addUser() {
Date hireDate = new Date();
User user = new User("name2", 2, "address2", hireDate);
userService.addUser(user);
}

public void updateUser() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date hireDate = null;
try {
hireDate = simpleDateFormat.parse("2005-01-01 08:30:20");
} catch (ParseException e) {
e.printStackTrace();
}
User user = new User(190, "name1", 10, "address100", hireDate);
userService.updateUser(user);
}

public void deleteUser() {
User user = new User();
user.setId(170);
userService.deleteUser(user);
}

public User queryUserById(Integer id) {
return userService.queryUserById(id);
}

public List<User> queryAllUser() {
return userService.queryAllUser();
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.course.controller.UserController;
import com.course.dao.UserDao;
import com.course.vo.User;

public class TestHibernateTemplate {

public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserController userController = (UserController) applicationContext.getBean("userController");

User user = userController.queryUserById(167);
System.out.println(user);
// Hibernate:
// select
// user0_.id as id1_0_0_,
// user0_.name as name2_0_0_,
// user0_.age as age3_0_0_,
// user0_.address as address4_0_0_,
// user0_.hire_date as hire_dat5_0_0_
// from
// User user0_
// where
// user0_.id=?
// User [id=167, name=name1, age=1, address=address1, hireDate=2022-03-18 16:33:44.0]
}
}

application-dao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 解析配置文件 -->
<!--
${username}在Spring里默认取的是当前的主机名,
如果想禁用取主机名可以使用system-properties-mode="FALLBACK"
-->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"/>

<!-- 声明数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 注入相关属性 -->
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>

<!-- 声明sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 取消使用hibernate.cfg.xml,在application-dao.xml文件中注入相关属性 -->
<!-- 注入mapping文件 -->
<property name="mappingLocations">
<array>
<value>com/course/vo/User.hbm.xml</value>
</array>
</property>
<!-- 注入其他配置 -->
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hbm2ddl.auto">update</prop>
<!--
以下属性好像没有起作用:
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
-->
</props>
</property>
</bean>

<!-- 创建hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<!-- 注入数据源 -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 声明Dao -->
<bean id="userDao" class="com.course.dao.impl.UserDaoImpl">
<!-- 注入jdbcTemplate -->
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>

application-service.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 声明式事务的配置开始 -->
<!-- 1.声明事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<!-- sessionFactory->session->transaction -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- 2.声明通知方式 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<!-- 配置那些方法要加入事务 -->
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 3.进行AOP配置 -->
<aop:config>
<!-- 声明切面 -->
<!-- 事务应该加在service层,不应该加在dao层 -->
<aop:pointcut id="pc" expression="execution(* com.course.service.impl.*.*(..))"/>
<!-- 织入 -->
<aop:advisor advice-ref="advice" pointcut-ref="pc"/>
</aop:config>
<!-- 声明式事务的配置结束 -->

<!-- 声明Service -->
<bean id="userService" class="com.course.service.impl.UserServiceImpl" autowire="byType"></bean>
</beans>

application-controller.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 声明Controller -->
<bean id="userController" class="com.course.controller.UserController" autowire="byType"></bean>
</beans>

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!-- 头文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
<import resource="classpath:application-controller.xml"/>
</beans>

db.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/spring_test
user=root
password=123456

log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=INFO, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n