springMVC4.3+hibernate5.4+freemarker2.3.28框架搭建

本文详细介绍如何将Spring MVC与Hibernate进行整合,包括Maven项目的搭建、数据库连接配置、使用Freemarker作为模板引擎以及实现增删改查等功能。此外还提供了完整的pom.xml文件、界面展示效果及源代码下载链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

创建maven项目

设置settings.xml

mysql

添加依赖

目录结构

web.xml

applicationContext.xml

dispatcher-servlet.xml

UserController

userList.ftl

addUser.ftl

editUser.ftl

界面展示

完整pom.xml

源代码下载:

附:HibernateSessionFactory.java

一对多配置


创建maven项目

设置settings.xml

<profile>
	<id>jdk-1.8</id>
	<activation>
		<activeByDefault>true</activeByDefault>
		<jdk>1.8</jdk>
	</activation>
	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
	</properties>
</profile>

 

maven添加archetypeCatalog = internal,解决maven项目速度慢的问题

另外可以修改默认设置解决maven慢的问题

 

mysql

jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false

添加依赖

<dependency>
	<groupId>c3p0</groupId>
	<artifactId>c3p0</artifactId>
	<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.28</version>
</dependency>

目录结构

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml /WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>

applicationContext.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 启用spring mvc 注解 -->
    <mvc:annotation-driven/>
    <!-- 自动扫描装配 -->
    <context:component-scan base-package="com.ibm.moses"/>
    <!--配置freemarker视图解析器 -->
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/views/"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>

    <bean id="ViewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="suffix" value=".ftl"/>
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="exposeRequestAttributes" value="true"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="requestContextAttribute" value="request"/>
        <property name="cache" value="true"/>
        <property name="order" value="0"/>
    </bean>
</beans>

dispatcher-servlet.xml

<?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"
       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">
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl"
                  value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 配置SessionFactory 通过spring提供的LocalSessionFactoryBean进行配置 -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.ibm.moses.*.model"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">
                    <![CDATA[jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false]]></prop>
                <prop key="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</prop>
            </props>
        </property>
    </bean>
    <!-- 配置一个事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <context:annotation-config/>
    <context:component-scan base-package="com.ibm.moses.*.service"/>
    <context:component-scan base-package="com.ibm.moses.*.dao"/>
</beans>

UserController

/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.controller
 * @version V1.0
 */
package com.ibm.moses.user.controller;

import com.ibm.moses.user.model.UserEntity;
import com.ibm.moses.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Moses *
 * @Date 2019/4/2
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/getUserList")
    public String getUserList(Model model) {
        model.addAttribute("userList", userService.getUserList());
        return "/user/userList";
    }

    @RequestMapping("/getUser")
    public String getUser(long id, Model model) {
        model.addAttribute("user", userService.getUser(id));
        return "/user/editUser";
    }

    @RequestMapping("/toAddUser")
    public String toAddUser() {
        return "/user/addUser";
    }

    @RequestMapping("/addUser")
    public String addUser(UserEntity User, Model model) {
        userService.addUser(User);
        model.addAttribute("userList", userService.getUserList());
        return "/user/userList";
    }

    @RequestMapping("/delUser")
    public String delUser(long id, Model model) {
        userService.delUser(id);
        model.addAttribute("userList", userService.getUserList());
        return "/user/userList";
    }

    @RequestMapping("/updateUser")
    public String updateUser(UserEntity user, Model model) {
        userService.updateUser(user);
        model.addAttribute("userList", userService.getUserList());
        return "/user/userList";
    }
}
UserService
/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.user.dao
 * @version V1.0
 */
package com.ibm.moses.user.service;

import com.ibm.moses.user.model.UserEntity;

import java.util.List;

/**
 * @author Moses *
 * @Date 2019/4/3
 */
public interface UserService {
    UserEntity getUser(long id);

    List<UserEntity> getUserList();

    void addUser(UserEntity userEntity);

    void delUser(long id);

    void updateUser(UserEntity userEntity);
}
UserServiceImpl
/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.user.dao
 * @version V1.0
 */
package com.ibm.moses.user.service.impl;

import com.ibm.moses.user.dao.UserDao;
import com.ibm.moses.user.model.UserEntity;
import com.ibm.moses.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Moses *
 * @Date 2019/4/3
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserEntity getUser(long id) {
        return userDao.getUser(id);
    }

    @Override
    public List<UserEntity> getUserList() {
        return userDao.getUserList();
    }

    @Override
    public void addUser(UserEntity userEntity) {
        userDao.addUser(userEntity);
    }

    @Override
    public void delUser(long id) {
        userDao.delUser(id);
    }

    @Override
    public void updateUser(UserEntity userEntity) {
        userDao.updateUser(userEntity);
    }
}

UserDao
/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.user.dao
 * @version V1.0
 */
package com.ibm.moses.user.dao;

import com.ibm.moses.user.model.UserEntity;

import java.util.List;

/**
 * @author Moses *
 * @Date 2019/4/3
 */
public interface UserDao {
    UserEntity getUser(long id);

    List<UserEntity> getUserList();

    void addUser(UserEntity userEntity);

    void delUser(long id);

    void updateUser(UserEntity userEntity);
}
UserDaoImpl
/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.user.dao
 * @version V1.0
 */
package com.ibm.moses.user.dao.impl;

import com.ibm.moses.common.BaseDao;
import com.ibm.moses.user.dao.UserDao;
import com.ibm.moses.user.model.UserEntity;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Moses *
 * @Date 2019/4/3
 */
@Repository
public class UserDaoImpl extends BaseDao<UserEntity> implements UserDao {
    @Override
    public UserEntity getUser(long id) {
        String hql = "from UserEntity p where p.id = ?0";
        return queryHQLList(hql, id).get(0);
    }

    @Override
    public List<UserEntity> getUserList() {
        String hql = "from UserEntity";
        return queryHQLList(hql);
    }

    @Override
    public void addUser(UserEntity userEntity) {
        executeCUD(userEntity, "C");
    }

    @Override
    public void delUser(long id) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        executeCUD(userEntity, "D");
    }

    @Override
    public void updateUser(UserEntity userEntity) {
        executeCUD(userEntity, "U");
    }
}

BaseDao
/*
 * Copyright © 2019 bjfansr@cn.ibm.com Inc. All rights reserved
 * @package: com.ibm.moses.common.dao
 * @version V1.0
 */
package com.ibm.moses.common;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Moses *
 * @Date 2019/4/4
 */
@SuppressWarnings("unchecked")
@Repository
public class BaseDao<T> {
    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.openSession();
    }

    public void executeCUD(T obj, String method) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.getTransaction();
            transaction.begin();
            switch (method) {
                case "C":
                    session.save(obj);
                    break;
                case "U":
                    session.update(obj);
                    break;
                case "D":
                    session.delete(obj);
                    break;
                default:
                    break;
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    public List<T> queryHQLList(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        return query.list();
    }

    public List<T> executeJDBCSqlQuery(String sql, Class clazz, List<String> params) {
        NativeQuery nativeQuery = getSession().createNativeQuery(sql, clazz);
        for (int i = 0; i < params.size(); i++) {
            nativeQuery.setParameter(i, params.get(i));
        }
        return nativeQuery.getResultList();
    }

}

userList.ftl

<#assign ctx = request.contextPath />
<!DOCTYPE html>
<html>
<head lang="zh">
    <base id="ctx" href="${ctx}">
    <title>用户信息</title>
    <script type="text/javascript" src="${ctx}/js/common/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function del(id) {
            $.get("${ctx}/user/delUser.form?id=" + id, function (data) {
                if ("success" == data.result) {
                    alert("删除成功");
                    window.location.reload();
                } else {
                    alert("删除失败");
                }
            });
        }
    </script>
</head>
<body>
<h3><a href="${ctx}/user/toAddUser.form">添加用户</a></h3>
<table border="1">
    <tbody>
    <tr>
        <th>姓名</th>
        <th>邮箱</th>
        <th>年龄</th>
        <th>操作</th>
    </tr>
    </tbody>
     <#list userList as user>
      <tr>
          <td>${user.name }</td>
          <td>${user.email }</td>
          <td>${user.age }</td>
          <td>
              <a href="${ctx}/user/getUser.form?id=${user.id }">编辑</a>
              <a href="${ctx}/user/delUser.form?id=${user.id }">删除</a>
          </td>
      </tr>
     </#list>
</table>
</html>

addUser.ftl

<#assign ctx = request.contextPath />
<!DOCTYPE html>
<html>
<head lang="zh">
    <base id="ctx" href="${ctx}">
    <title>用户信息</title>
    <script type="text/javascript" src="${ctx}/js/common/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function addUser(){
            var form = document.forms[0];
            form.action = "${ctx}/user/addUser.form";
            form.method="post";
            form.submit();
        }
    </script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
    姓名:<input type="text" name="name">
    邮箱:<input type="text" name="email">
    年龄:<input type="text" name="age">
    <input type="button" value="添加" onclick="addUser()">
</form>
</body>
</html>

editUser.ftl

<#assign ctx = request.contextPath />
<!DOCTYPE html>
<html>
<head lang="zh">
    <base id="ctx" href="${ctx}">
    <title>用户信息</title>
    <script type="text/javascript" src="${ctx}/js/common/jquery-3.3.1.min.js"></script>
</head>
<body>
<h1>编辑用户</h1>
<form action="${ctx}/user/updateUser.form" name="userForm" method="post">
    <input type="hidden" name="id" value="${user.id}">
    姓名:<input type="text" name="name" value="${user.name}">
    姓名:<input type="text" name="email" value="${user.email}">
    姓名:<input type="text" name="age" value="${user.age}">
    <input type="submit" value="编辑" >
</form>
</body>
</html>

界面展示

http://localhost:8080/moses-spring-hibernate/user/getUserList.form

http://localhost:8080/moses-spring-hibernate/user/toAddUser.form

http://localhost:8080/moses-spring-hibernate/user/delUser.form?id=12

完整pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ibm.moses</groupId>
    <artifactId>moses-spring-hibernate</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>moses-spring-hibernate Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <spring.version>5.0.0.RELEASE</spring.version>
        <hibernate.version>5.2.11.Final</hibernate.version>
        <hibernate.validator>5.4.1.Final</hibernate.validator>
        <c3p0.version>0.9.5.4</c3p0.version>
        <jstl.version>1.2.1</jstl.version>
        <tld.version>1.1.2</tld.version>
        <servlets.version>3.1.0</servlets.version>
        <jsp.version>2.3.1</jsp.version>
        <hsqldb.version>1.8.0.10</hsqldb.version>
        <mysql.version>8.0.11</mysql.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <!-- spring-context-support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring MVC Dependency -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Hibernate ORM -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- Hibernate-C3P0 Integration -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- Hibernate Validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator}</version>
        </dependency>
        <!-- JSTL Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>${tld.version}</version>
        </dependency>
        <!-- Servlet Dependency -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlets.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSP Dependency -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- HSQL Dependency -->
        <dependency>
            <groupId>hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>${hsqldb.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>moses-spring-hibernate</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

源代码下载:

https://github.com/glory2018/moses-spring-hibernate.git

附:HibernateSessionFactory.java

package com.ibm.moses.common;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
	
    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

	static {
    	try {
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure();
			serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
			try {
				sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
			} catch (Exception e) {
				StandardServiceRegistryBuilder.destroy(serviceRegistry);
				e.printStackTrace();
			}
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

一对多配置

import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;

/**
 * @author Moses
 * @Date 2019/4/26
 */
@Entity
@Table(name = "TB_MS_BASIC", schema = "AIIB_MS", catalog = "")
public class TbMsBasicEntity {
    private int msBasicId;

    private List<TbMsDetailEntity> detailEntityList;


    @Id
    @Column(name = "MS_BASIC_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @SequenceGenerator(name = "generator", sequenceName = "SEQ_MS_BASIC_ID")
    public int getMsBasicId() {
        return msBasicId;
    }

    public void setMsBasicId(int msBasicId) {
        this.msBasicId = msBasicId;
    }

      

    @OneToMany(mappedBy = "detailEntityList")
    public List<TbMsDetailEntity> getDetailEntityList() {
        return detailEntityList;
    }

    public void setDetailEntityList(List<TbMsDetailEntity> detailEntityList) {
        this.detailEntityList = detailEntityList;
    }
}
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;

/**
 * @author Moses
 * @Date 2019/4/26
 */
@Entity
@Table(name = "TB_MS_DETAIL", schema = "AIIB_MS", catalog = "")
public class TbMsDetailEntity {
    private int msDetailId;
    private Integer msBasicId;

    private TbMsBasicEntity detailEntityList;

    @Id
    @Column(name = "MS_DETAIL_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @SequenceGenerator(name = "generator", sequenceName = "SEQ_MS_DETAIL_ID")
    public int getMsDetailId() {
        return msDetailId;
    }

    public void setMsDetailId(int msDetailId) {
        this.msDetailId = msDetailId;
    }

    @Basic
    @Column(name = "MS_BASIC_ID", insertable = false, updatable = false)
    public Integer getMsBasicId() {
        return msBasicId;
    }

    public void setMsBasicId(Integer msBasicId) {
        this.msBasicId = msBasicId;
    }



    @ManyToOne
    @JoinColumn(name = "MS_BASIC_ID", referencedColumnName = "MS_BASIC_ID")
    public TbMsBasicEntity getDetailEntityList() {
        return detailEntityList;
    }

    public void setDetailEntityList(TbMsBasicEntity detailEntityList) {
        this.detailEntityList = detailEntityList;
    }
}

事务

1.更新实体

private int executeCUD(T obj, String method) {
        int result = 0;
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.getTransaction();
            transaction.begin();
            switch (method) {
                case "C":
                    result = (int) session.save(obj);
                    break;
                case "U":
                    session.merge(obj);
                    break;
                case "D":
                    session.delete(obj);
                    break;
                default:
                    break;
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw new RuntimeException(e.getMessage());
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return result;
    }

2.更新hql

public int executeUpdateHql(String hql, Object... params) {
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery(hql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i, params[i]);
            }
        }
        int updatedEntities = query.executeUpdate();
        tx.commit();
        session.close();
        return updatedEntities;
    }

3.配置事务

Spring的配置文件会跳过@Controller注解;而Springmvc的配置文件只会扫描@Controller。

Springmvc配置中的use-default-filters="false"是必须要有的!如果不写上,它的默认值是true,而这个default-filters会默认扫描@Service、@Repository等注解,这样就会和Spring的配置发生冲突!

dispatcher-servlet.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- mvc注解 -->
    <mvc:annotation-driven/>
    <!-- 扫描 -->
    <context:component-scan base-package="com.ibm.xxx" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--配置freemarker视图解析器 -->
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/views/"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
    <bean id="ViewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="suffix" value=".ftl"/>
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="exposeRequestAttributes" value="true"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="requestContextAttribute" value="request"/>
        <property name="cache" value="true"/>
        <property name="order" value="0"/>
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20848820"/>
    </bean>
    <!-- 解析静态资源 -->
    <mvc:default-servlet-handler/>
    <mvc:view-controller path="/" view-name="redirect:/jacob/getBasicList"/>
</beans>

applicationContext.xml

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 扫描注解,注册bean -->
    <context:component-scan base-package="com.ibm.xxx">
        <!-- 跳过@Controller -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
    <!-- 配置数据源 -->
    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 配置SessionFactory 通过spring提供的LocalSessionFactoryBean进行配置 -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.ibm.xxx.model"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>
    </bean>
    <!-- 开启通过注解@Transactional管理事务 -->
    <!--    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />-->
    <!-- =============配置事务 start============= -->
    <!-- 配置Spring 的声明式事务 -->
    <!-- 1.配置事务管理器.   *看清楚hibernate的版本-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 2.配置事务属性,需要事务管理器-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--    如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。-->
            <tx:method name="insert*" rollback-for="java.lang.Exception" propagation="REQUIRED"/>
            <tx:method name="update*" rollback-for="java.lang.Exception" propagation="REQUIRED"/>
            <tx:method name="delete*" rollback-for="java.lang.Exception" propagation="REQUIRED"/>
            <!--    支持当前事务,如果当前没有事务,就以非事务方式执行。-->
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <!-- 其他采用默认事务方式 -->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 3.配置事务切点,并把切点和事务管理器关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.ibm.xxx.*.service.*.*(..))" id="point-cut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="point-cut"/>
    </aop:config>
</beans>

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            classpath*:applicationcontext-*.xml
        </param-value>
    </context-param>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

dao

 private Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    public int addEntity(T t) {
        return (int) getSession().save(t);
    }

    @Override
    public void updateEntity(T t) {
        getSession().update(t);
    }

    @Override
    public void deleteEntity(T t) {
        getSession().delete(t);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值