MyBatis使用注解实现增删改查

32 篇文章 0 订阅
20 篇文章 0 订阅

使用Spring与MyBatis整合,即把mybatis数据源的配置、事务的管理、SqlSessionFactory的创建以及数据映射器接口Mapper的创建交由spring去管理”,所以mybatis的配置文件mybatis-config.xml中不需要再配置数据源及事务,在业务层service实现时不需要手动地获取SqlSession以及对应的数据映射器接口Mapper,通过spring的注入即可。

build.gradle

group 'com.xiya'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'idea'

sourceCompatibility = 1.8

repositories {
    maven {
        url 'http://maven.aliyun.com/nexus/content/groups/public/'
    }
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.40'
    compile group: 'org.springframework', name: 'spring-context', version: '4.3.7.RELEASE'
    compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.7.RELEASE'
    compile group: 'org.mybatis', name: 'mybatis', version: '3.4.4'
    compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.1'
    compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'
    compile group: 'log4j', name: 'log4j', version: '1.2.17'
    compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
    compile group: 'commons-dbutils', name: 'commons-dbutils', version: '1.6'
}

tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}
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">

    <context:property-placeholder location="classpath:jdbc.properties"/>

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

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="cn.bjut.mapper.PersonMapper"/>
    </bean>

</beans>
PersonMapper.java
package cn.bjut.mapper;

import cn.bjut.entity.Person;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * Created by N3verL4nd on 2017/6/6.
 */
public interface PersonMapper {
    @Select("SELECT * FROM persons WHERE id = #{id}")
    Person selectPerson(int id);

    @Select("SELECT * FROM persons")
    List<Person> selectAllPerson();

    @Delete("DELETE FROM persons WHERE id = #{id}")
    void deletePerson(int id);

    @Update("UPDATE persons SET name = #{name}, age = #{age} where id = #{id}")
    void update(Person person);

    @Insert("INSERT INTO persons(name, age) VALUES(#{name}, #{age})")
    void insert(Person person);
}
我们使用注解替换了映射文件,实际上,MyBatis的配置文件也是可以省略的,因为大部分的内容我们都交由Spring管理了。

测试:

import cn.bjut.entity.Person;
import cn.bjut.mapper.PersonMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by N3verL4nd on 2017/6/6.
 */
public class T {

    @Test
    public void test() {
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
        Person person = personMapper.selectPerson(1);
        System.out.println(person);
        sqlSession.close();
    }

    @Test
    public void testSM() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        PersonMapper personMapper = ctx.getBean(PersonMapper.class);
        //Person person = personMapper.selectPerson(1);
        //System.out.println(person);
        List<Person> list = personMapper.selectAllPerson();
        list.forEach(System.out::println);

        //DELETE
        //personMapper.deletePerson(8);

        //UPDATE
        //Person person = personMapper.selectPerson(9);
        //person.setAge(30);
        //personMapper.update(person);

        //INSERT
        //Person person = new Person("李广辉", 25);
        //personMapper.insert(person);

        //SELECT
        //list = personMapper.selectAllPerson();
        //list.forEach(System.out::println);
    }
}
整体结构图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值