Loading

SSM整合配置笔记

首先新建maven项目,导入相关的依赖,junit,mysql,c3p0,servlet,jsp,jstl,mybatis,mybatis-spring,spring-webmvc,spring-jdbc

建立dao,service,controller,pojo,新建mybatis-config.xml,applicationContext.xml

MyBatis层

  1. 新建数据库配置文件database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
  1. IDEA关联数据库
  2. 在mybatis-config.xml中配置
<!--让spring去配置数据源-->

<typeAliases>
    <package name="com.hjc.pojo"/>
</typeAliases>
  1. 编写实体类
public class User {
    private int userId;
    private String userName;
    private String address;
    
    //省略get/set,toString方法
}
  1. 编写UserMapper接口
public interface UserMapper {
    int addUser(User user);
    int deleteUserById(@param("userId") int id);
    int updateUser(User user);
    User findUserById(@param("userId") int id);
    List<User> findAllUser();
}
  1. 在resources文件夹下新建com/hjc/dao/UserMapper.xml,注意不是包路径,是文件夹路径
<mapper namespace="com.hjc.dao.UserMapper">
    <insert id="addUser" parameterType="User">
        insert into user (userId, userName, address) values (#{userId}, #{userName}, #{address})
    </insert>
    <delete id="deleteUserById" parameterType="int">
        delete from user where userId = #{userId}
    </delete>
    <update id="updateUser" parameterType="User">
        update user set userName = #{userName}, address = #{address} where userId = #{userId}
    </update>
    <select id="findUserById" parameterType="int" resultType="User">
        select * from user where userId = #{userId}
    </select>
    <select id="findAllUser" resultType="User">
        select * from user
    </select>
</mapper>
  1. 在mybatis-config.xml中注册UserMapper
<mappers>
    <mapper resource="com/hjc/dao/UserMapper.xml"/>
</mappers>
  1. 编写UserService接口
public interface UserService {
    int addUser(User user);
    int deleteUserById(int id);
    int updateUser(User user);
    User findUserById(int id);
    List<User> findAllUser();
}
  1. 编写UserService接口的实现类UserServiceImpl
public class UserServiceImpl implements UserService {
    
    private UserMapper userMapper;
    
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    
    public int addUser(User user) {
        return userMapper.addUser(user);
    }
    
    public int deleteUserById(int id) {
        return userMapper.deleteUserById(id);
    }
    
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }
    
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }
    
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }
}

Spring层

  1. 新建spring-dao.xml注册dao层的类
<!--关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>

<!--配置连接池,使用c3p0,也可以使用Spring原生的连接池或其他连接池-->
<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>

<!--本来会配置JdbcTemplate操作数据库,但现在使用MyBatis-->
<!--注册sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--绑定mybatis-config.xml-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

<!--配置sqlSessionTemplate-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
  1. 编写UserMapper接口的实现类UserMapperImpl
public class UserMapperImpl implements UserMapper {
    
    private SqlSession sqlSession;
    
    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
    
    public int addUser(User user) {
        return sqlSession.getMapper(UserMapper.class).addUser(user);
    }
    
    public int deleteUserById(int id) {
        return sqlSession.getMapper(UserMapper.class).deleteUserById(id);
    }
    
    public int updateUser(User user) {
        return sqlSession.getMapper(UserMapper.class).updateUser(user);
    }
    
    public User findUserById(int id) {
        return sqlSession.getMapper(UserMapper.class).findUserById(id);
    }
    
    public List<User> findAllUser() {
        return sqlSession.getMapper(UserMapper.class).findAllUser();
    }
}
  1. 在spring-dao.xml中配置实现类,也可以使用注解配置
<bean id="userMapper" class="com.hjc.dao.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>
  1. 另一种方法

上述方法是通过配置sqlSessionTemplate来手动实现UserMapperImpl实现类,并将其配置到bean中供service层调用

但是,还有一种方法可以不用手动实现mapper层的实现类,而让service层直接调用。也就是说,上述操作1中的配置sqlSessionTemplate到操作3中的步骤都可以省去

一般使用MyBatis不需要编写dao层的实现类,因为MyBatis会自动生成dao层的代理对象来实现对数据库的操作,但是这个代理对象一般无法获取到,但我们可以通过配置MapperScannerConfigurer将dao接口的代理对象自动加入到容器中

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.hjc.dao">
</bean>

这样就将dao接口的实现自动加入到了IOC容器中。这样的话,在service层的实现类中,因为获取不到容器中dao接口实现类的id,所以我们需要使用@Autowired注解自动注入实现类

  1. 新建spring-service.xml
<!--扫描service包-->
<context:component-scan base-package="com.hjc.service"/>

<!--将业务类注入到spring,通过配置或者注解实现-->
<bean id="userService" class="com.hjc.service.UserServiceImpl">
    <property name="userMapper" ref="userMapper"/>
</bean>
<!--注解实现:在UserServiceImpl类名上加上@Service,在set方法上加上@Autowired-->

<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!--基于xml配置事务-->
<aop:config>
    <aop:pointcut id="txPoint" expression="excution(* com.hjc.service.*.*(..))"/>
    <aop:advisor advice-ref="" pointcut-ref="txPoint"/>
</aop:config>

<!--配置事务增强方法-->
<tx:advice id="myTx" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" rollback-for="java.lang.Exception">
        <tx:method name="get*" read-only="true">
    </tx:attributes>
</tx:advice>

当然,上述方法中的配置事务可以使用注解@Transactional来代替,具体配置可以参考Spring中的事务管理

SpringMVC层

  1. 配置web.xml
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>encodingFilter</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>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>15</session-timeout>
</session-config>
  1. 配置spring-mvc.xml
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.hjc.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
  1. 在applicationContext.xml中导入三个xml
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>

至此,基本的环境已经搭建完毕,接下来就是实现业务

业务

实现查询所有用户的功能

  1. 编写UserController
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;
    
    //查询所有用户
    @RequestMapping("/allUser")
    public String getAllUser(Model model) {
        List<User> userList = userService.findAllUser();
        model.addAttribute("list", userList);
        return "allUser"
    }
}
  1. 在jsp目录下新建allUser.jsp
<html>
    <head>
        <title>所有用户</title>
        <%--BootStrap--%>
        <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
            
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <div class="page-header">
                        <h1>
                            <small>用户列表---------显示所有用户</small>
                        </h1>
                    </div>
                </div>
            </div>
            
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <table class="table table-hover table-striped">
                        <thead>
                            <tr>
                                <th>用户编号</th>
                                <th>用户姓名</th>
                                <th>用户地址</th>
                            </tr>
                        </thead>
                        <%--数据从list中遍历出来--%>
                        <tbody>
                            <c:forEach var="user" items="${list}">
                                <tr>
                                    <td>${user.userId}</td>
                                    <td>${user.userName}</td>
                                    <td>${user.address}</td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
            
        </div>
    </body>
</html>
  1. 在index.jsp中编写
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>首页</title>
        <style>
            a{
                text-decoration: none;
                color: black;
                font-size: 18px;
            }
            h3{
                width: 180px;
                height: 38px;
                margin: 100px auto;
                text-align: center;
                line-height: 38px;
                background: deepskyblue;
                border-radius: 5px;
            }
        </style>
    </head>
    <body>
        <h3>
            <a href="${pageContext.request.contextPath}/user/allUser">查看所有用户</a>
        </h3>
    </body>
</html>
posted @ 2020-07-20 00:04  Kinopio  阅读(116)  评论(0编辑  收藏  举报