Spring与MyBatis的整合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35512245/article/details/53749319

首先看一下项目结构图:

具体步骤如下:

1、建立JDBC属性文件

jdbc.properties (文件编码修改为 utf-8 )

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/projectview
username=root
password=729821

辅助:数据库脚本:

INSERT INTO `test_user` VALUES (1, 'liuzhonghao', '6329869', '384037404@qq.com');
INSERT INTO `test_user` VALUES (2, 'xiahe', '6329869', '12345@qq.com');
INSERT INTO `test_user` VALUES (3, NULL, NULL, NULL);
INSERT INTO `test_user` VALUES (4, '123', '123', '123');
INSERT INTO `test_user` VALUES (5, '321', '321', '321');

2、log4j的配置

#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B
log4j.rootLogger=INFO,Console,File
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6
log4j.appender.File =org.apache.log4j.RollingFileAppender
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55
log4j.appender.File.File = logs/ssm.log
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F
log4j.appender.File.MaxFileSize = 10MB
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout =org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-ddHH\:mm\:ss}][%c]%m%n

3、建立工程

(1)User类

package com.hqj.model;

public class User {
    private Integer id;

    private String username;

    private String password;

    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    public User(Integer id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password="
                + password + ", email=" + email + "]";
    }
}

(2)UserMapper类(Mybatis中的DAO类)

package com.hqj.dao;

import com.hqj.model.User;

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

(3)UserMapper类(Mybatis映射文件)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hqj.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.hqj.model.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, username, password, email
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from test_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from test_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.hqj.model.User" >
    insert into test_user (id, username, password, 
      email)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{email,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.hqj.model.User" >
    insert into test_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="email != null" >
        email,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.hqj.model.User" >
    update test_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.hqj.model.User" >
    update test_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

(4)UserService类(Spring中对应的类接口)

package com.hqj.service;

import com.hqj.model.User;

public interface UserService {
    public User getUserById(Integer id);
}

(5)UserServiceImpl类(Spring中对应的类接口的实现)

务必先看图片中的红字!易错点!!! 务必先看图片中的红字!易错点!!! 务必先看图片中的红字!易错点!!!

package com.hqj.serviceimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hqj.dao.UserMapper;
import com.hqj.model.User;
import com.hqj.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Integer id) {
        // TODO Auto-generated method stub
        return userMapper.selectByPrimaryKey(id);
    }

    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

}

(6)测试类

务必先看图片中的红字!易错点!!! 务必先看图片中的红字!易错点!!! 务必先看图片中的红字!易错点!!!

package com.hqj.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hqj.model.User;
import com.hqj.service.UserService;

public class test1 {

    @Test
    public void testsearch() {
        ApplicationContext ctx = null;
        ctx = new ClassPathXmlApplicationContext("spring-mybatis.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        User user = userService.getUserById(1);
        System.out.println(user);
    }
}

(7)spring-mybatis.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.1.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hqj.serviceimpl" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/hqj/mapping/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hqj.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

测试成功的结果如下:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏菩提树下的杨过

ExtJs+WCF+LINQ实现分页Grid

上篇文章《用ExtJs+Linq+Wcf打造简单grid 》,这个网格控件不带分页,本文在上文的基础上添加分页功能,文中会着重介绍如何在用LINQ返回分页数据,...

36470
来自专栏Golang语言社区

在Go中使用服务对象模式

NOTE: Most of the code and ideas in this post are things I have been experimenti...

11320
来自专栏高性能服务器开发

(三) 服务器端的程序架构介绍2

下面我们以pc端登录为例来具体看一个数据包在服务器端各个服务之间走过的流程: 步骤1:login_server初始化侦听socket,设置新连接到来的回调函数。...

43050
来自专栏菩提树下的杨过

java学习:Hibernate学习-用oracle sequence序列生成ID的配置示例

接上回继续,TMP_EMP中的ID是根据序列SQ_TMP_EMP来生成的,需要在TmpEmp.hbm.xml中设置:   <id name="id" type=...

21690
来自专栏debugeeker的专栏

sedna进行xquery查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuzhina/article/detai...

8910
来自专栏Golang语言社区

Golang生产级可靠UDP库

kcp-go is a Production-Grade Reliable-UDP library for golang.

81920
来自专栏游戏杂谈

基于SOUI开发一个简单的小工具

Duilib 很久不维护了,而很多不同的分支,似乎都不太维护。微信 Windows 的版本是基于 Duilib 进行开发的,说明应该还是很广泛的。

46230
来自专栏

Flex 上传文件,服务端.net

using System; using System.Data; using System.Configuration; using System.Collec...

7710
来自专栏菩提树下的杨过

.NET:Entity Framework 笔记

有二年没关注EF,今天无意试了下发现跟主流的Hibernate等ORM框架越来越接近了,先看下Entity类的定义: using System; using S...

22080
来自专栏Golang语言社区

Go中的依赖注入

I have written a small utility package to handle dependency injection in Go (it'...

27440

扫码关注云+社区

领取腾讯云代金券