欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring-Mybatis的业务实现的几种方式

程序员文章站 2022-05-24 20:18:28
...

Spring-Mybatis的业务实现的三种方式

1、新建Maven项目

2、导入依赖

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.23</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.4</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.0.8.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.0.8.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>5.0.8.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.0.8.RELEASE</version>
</dependency>

3、对应数据库建立实体类

Spring-Mybatis的业务实现的几种方式

无参构造函数、getter和setter还有toString方法

User.java:

@Component
public class User {
    private int uid;
    private String username;
    private String password;
    private int age;

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

4、编写Mapper接口

完成CRUD(增删改查)的需求

UserMapper.java:

public interface UserMapper {
    //查询所有用户
    List<User> selectAllUser();
    //根据id查询用户
    User selectUserById(int uid);
    //根据username模糊查询
    List<User> selectUserLikeUsername(String username);
    //新增用户(主键自增)
    int insertUser(User user);
}

5、编写Mapper接口对应的Mapper.xml文件

强烈建议Mapper接口文件和Mapper.xml文件在同一个包下

<namespace>对应接口的类限定名

对应的CRUD的标签的id对应Mapper接口的方法名字,返回值和传入参数也要对应

UserMapper.xml

<?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="cn.yznu.mapper.UserMapper">
    <select id="selectAllUser" resultType="User">
        SELECT
            *
        FROM
            user
    </select>
    <select id="selectUserById" parameterType="integer" resultType="User">
        SELECT
            *
        FROM
            user
        WHERE
            uid=#{uid}
    </select>
    <select id="selectUserLikeUsername" parameterType="string" resultType="User">
        SELECT
            *
        FROM
            user
        WHERE
            username LIKE "%"#{username}"%"
    </select>
    <insert id="insertUser" parameterType="User"
            keyProperty="uid" useGeneratedKeys="true">
        INSERT INTO
            user
        (username,password,age)
        VALUES
        (#{username},#{password},#{age})
    </insert>
</mapper>

6、properties属性文件

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/表名?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
jdbc.username=数据库用户名
jdbc.password=数据库密码

7、mybatis-config配置文件

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="cn.yznu.pojo" />
    </typeAliases>
    <mappers>
        <mapper class="cn.yznu.mapper.UserMapper"/>
    </mappers>
</configuration>

8、spring-dao配置文件(建议单独写,再丢入Spring容器)

spring-config.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">
    <!--引入db.properties文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--    dataSource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--    sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!--    sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

9、Spring容器配置文件

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"
       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">
    <import resource="spring-dao.xml"/>
    <context:component-scan base-package="cn.yznu.pojo"/>
</beans>

10、编写Mapper接口的实现类

写实现类的目的就是为了先将sqlSession对象获取到,然后再将SqlSession对象跟Mapper接口的CRUD方法封装,避免以后在业务里每次都还需要去获取SqlSession对象。

第一种方式、用@Autowired自动装配SqlSession对象

UserMapperImpl.java:
public class UserMapperImpl implements UserMapper {
    @Autowired
    SqlSession sqlSession;
    @Override
    public List<User> selectAllUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectAllUser();
    }

    @Override
    public User selectUserById(int uid) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserById(uid);
    }

    @Override
    public List<User> selectUserLikeUsername(String username) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserLikeUsername(username);
    }

    @Override
    public int insertUser(User user) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.insertUser(user);
    }
}
然后再给UserMapper接口和UserMapperImpl实现类的头上添加@component注解并且在spring容器里添加component扫描,让spring能够托管它们:
@Component
public interface UserMapper {
@Component
public class UserMapperImpl implements UserMapper {
<?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">
    <import resource="spring-dao.xml"/>
    <context:component-scan base-package="cn.yznu.mapper"/>
    <context:component-scan base-package="cn.yznu.pojo"/>
</beans>
测试:

UserMapperTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class UserMapperTest {
    @Autowired
    UserMapper userMapper;
    @Autowired
    User user;
    @Test
    public void selectAllUser() {
        List<User> userList = userMapper.selectAllUser();
        System.out.println(userList);
    }

    @Test
    public void selectUserById() {
        User user = userMapper.selectUserById(1);
        System.out.println(user);
    }

    @Test
    public void selectUserLikeUsername() {
        List<User> userList = userMapper.selectUserLikeUsername("q");
        System.out.println(userList);
    }

    @Test
    public void insertUser() {
        user.setUsername("测试");
        userMapper.insertUser(user);
    }
}

因为UserMapper的接口和它的实现还有User都被我们丢到了spring容器,所以用@Autowired就可以直接用了,同时因为UserMapperImpl里面我们已经将sqlSession跟CRUD封装起来了,所以在测试里就不需要获取sqlSession对象了。

总结:在接口的实现类里,用Autowired获取到sqlSession对象,再返回sqlSession.getMapper()里的相应方法

第二种方式、在实现里用SqlSessionTemplate获取到sqlSess对象

去掉刚刚给UserMapper和UserMapperImpl头上加的@Component注解

再把刚刚的UserMapperImpl.java改成这样:

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;
    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession=sqlSession;
    }
    @Override
    public List<User> selectAllUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectAllUser();
    }

    @Override
    public User selectUserById(int uid) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserById(uid);
    }

    @Override
    public List<User> selectUserLikeUsername(String username) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserLikeUsername(username);
    }

    @Override
    public int insertUser(User user) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.insertUser(user);
    }
}

用SqlSessionTemplate获取sqlSession对象,再写一个setSqlSession方法

再到applicationContext容器里给这个setSqlSession注入SqlSession:

去掉刚刚的<context:component-scan base-package="cn.yznu.mapper"/>

<?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">
    <import resource="spring-dao.xml"/>
    <context:component-scan base-package="cn.yznu.pojo"/>
    <bean id="UserMapper" class="cn.yznu.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

测试:

UserMapperTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class UserMapperTest {
    @Autowired
    UserMapper userMapper;
    @Autowired
    User user;
    @Test
    public void selectAllUser() {
        List<User> userList = userMapper.selectAllUser();
        System.out.println(userList);
    }

    @Test
    public void selectUserById() {
        User user = userMapper.selectUserById(1);
        System.out.println(user);
    }

    @Test
    public void selectUserLikeUsername() {
        List<User> userList = userMapper.selectUserLikeUsername("q");
        System.out.println(userList);
    }

    /*@Test
    public void insertUser() {
        user.setUsername("测试");
        userMapper.insertUser(user);
    }*/
}

因为刚刚我们的UserMapperImpl里已经跟SqlSession封装好了,并且也在applicationContext容器中注入了,所以我们就可以直接在业务或者测试里面直接用@Autowired自动装配UserMapper对象了。

第三种方式、用实现类继承SqlSessionSupport类再获取sqlSession对象

继承SqlSessionSupport类之后,就可以直接使用getSqlSession()方法获得sqlSession对象了

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper  {
    @Override
    public List<User> selectAllUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectAllUser();
    }

    @Override
    public User selectUserById(int uid) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUserById(uid);
    }

    @Override
    public List<User> selectUserLikeUsername(String username) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUserLikeUsername(username);
    }

    @Override
    public int insertUser(User user) {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.insertUser(user);
    }
}

要在Spring容器里给UserMapper注入SqlSessionFactory

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"
       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">
    <import resource="spring-dao.xml"/>
    <context:component-scan base-package="cn.yznu.pojo"/>
    <bean id="UserMapper" class="cn.yznu.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

测试:

UserMapperTestjava

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class UserMapperTest {
    @Autowired
    UserMapper userMapper;
    @Autowired
    User user;
    @Test
    public void selectAllUser() {
        List<User> userList = userMapper.selectAllUser();
        System.out.println(userList);
    }

    @Test
    public void selectUserById() {
        User user = userMapper.selectUserById(1);
        System.out.println(user);
    }

    @Test
    public void selectUserLikeUsername() {
        List<User> userList = userMapper.selectUserLikeUsername("q");
        System.out.println(userList);
    }

    /*@Test
    public void insertUser() {
        user.setUsername("测试");
        userMapper.insertUser(user);
    }*/
}

由于我们在实现类里继承了sqlSessionSupport类然后调用getSqlSession()方法获取到了sqlSession对象,并且在Spring容器里也注入了SqlSessionFactory,所以我们就可以直接在测试或者业务里用@Autowired装配UserMapper对象

其中,第二种方式和第三种方式都是官网提到的方式,官网更推荐第三种:

http://mybatis.org/spring/zh/sqlsession.html

Spring-Mybatis的业务实现的几种方式

总结:

都是为了解耦而将sqlSession跟Mapper接口的CRUD封装,然后交给Spring容器管理,再在业务或者测试里用@Autowired自动装配就好了