整合 Spring MVC 与 Hibernate

pom.xml

1
2
3
4
5
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>

servlet.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
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="initialSize" value="5" />
    <property name="maxActive" value="10" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>io.github.josephpei.domain</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.use_sql_comments">false</prop>
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<tx:annotation-driven />

User.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Entity
@Table(name="user_tbl")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="user_id")
    @GeneratedValue
    private Long userId;

    @Column(name="user_name")
    private String userName;

    @Column(name="password")
    private String password;

    @Column(name="last_ip")
    private String lastIp;

    @Column(name="last_visit")
    private Date lastVisit;

    // omit getter and setter
}

HibUserDao.java

 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
@Repository
@SuppressWarnings("unchecked")
public class HibUserDao implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Long getMatchCount(String userName, String password) {
        String hql = "select count(*) from User where userName=:name and password=:pass";

        Query q = sessionFactory.getCurrentSession().createQuery(hql);
        q.setParameter("name", userName);
        q.setParameter("pass", password);

        Long row = 0L;
        for (Iterator it = q.iterate(); it.hasNext(); )
            row = (Long) it.next();
        return row;
    }

    @Override
    public User findUserByName(String userName) {
        Query q = sessionFactory.getCurrentSession().createQuery("from User where userName=:name");
        q.setParameter("name", userName);
        List<User> users = q.list();
        return (users.isEmpty() ? null : users.get(0));
    }

    @Override
    public void updateLoginInfo(User user) {
        sessionFactory.getCurrentSession().update(user);
    }

    @Override
    public void insertUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }
}

HibUserService.java

 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
@Service
public class HibUserService {
    @Autowired
    private HibUserDao hibUserDao;

    @Transactional
    public boolean hasMatchUser(String userName, String password) {
        Long count = hibUserDao.getMatchCount(userName, password);
        return count > 0;
    }

    @Transactional
    public User findUserByName(String userName) {
        return hibUserDao.findUserByName(userName);
    }

    @Transactional
    public void loginSuccess(User user) {
        hibUserDao.updateLoginInfo(user);
    }

    @Transactional
    public void insertUser(User user) {
        hibUserDao.insertUser(user);
    }
}