MyBatis CRUD Demo

conf.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--添加映射-->
        <mapper class="mybatis.UserMapper"/>
    </mappers>
</configuration>
映射:
/**
 * Created by ZhangZhengyi on 2016/3/7.
 */
public interface UserMapper {
    @Insert("insert into users(name, age) values(#{name}, #{age})")
    public int insertUser(User user);

    @Delete("delete from users where id=#{id}")
    public int deleteUserById(int id);

    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public int updateUser(User user);

    @Select("select * from users where id=#{id}")
    public User getUserById(int id);

    @Select("select * from users")
    public List<User> getAllUser();
}

javaBean:
/**
 * Created by ZhangZhengyi on 2016/3/7.
 */
public class User {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

测试类:
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * Created by ZhangZhengyi on 2016/3/7.
 */
public class TestCRUDByAnnotationMapper {

    public void addUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        //得到UserMapper接口的实现类对象,UserMapper接口的实现类对象由sqlSession.getMapper(UserMapper.class)动态构建出来
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setName("新用户");
        user.setAge(23);
        user.setId(999);
        int add = mapper.insertUser(user);
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        System.out.println(add);
    }

    public void updateUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        //得到UserMapper接口的实现类对象,UserMapper接口的实现类对象由sqlSession.getMapper(UserMapper.class)动态构建出来
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(3);
        user.setName("什么鬼");
        user.setAge(26);
        //执行修改操作
        int retResult = mapper.updateUser(user);
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        System.out.println(retResult);
    }

    public void deleteUser(int id){
        SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
        //得到UserMapper接口的实现类对象,UserMapper接口的实现类对象由sqlSession.getMapper(UserMapper.class)动态构建出来
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行删除操作
        int retResult = mapper.deleteUserById(id);
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        System.out.println(retResult);
    }


    public User getUser(int id){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //得到UserMapper接口的实现类对象,UserMapper接口的实现类对象由sqlSession.getMapper(UserMapper.class)动态构建出来
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行查询操作,将查询结果自动封装成User返回
        User user = mapper.getUserById(id);
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        return user;
    }
    public List<User> getAll(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //得到UserMapper接口的实现类对象,UserMapper接口的实现类对象由sqlSession.getMapper(UserMapper.class)动态构建出来
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行查询操作,将查询结果自动封装成List<User>返回
        List<User> lstUsers = mapper.getAllUser();
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        return lstUsers;
    }

    public static void main(String[] args) {
        TestCRUDByAnnotationMapper annotationMapper = new TestCRUDByAnnotationMapper();
        List<User> all = annotationMapper.getAll();
        for (User user : all) {
            System.out.println(user.getName());
        }
    }
} 
工具类:
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * Created by ZhangZhengyi on 2016/3/7.
 */
public class MyBatisUtil {
    public static SqlSessionFactory getSqlSessionFactory() {
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream("conf.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//读取配置文件
        return factory;
    }
    /**
     * 23      * 获取SqlSession
     * 24      * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }

    /**
     * 31      * 获取SqlSession
     * 32      * @param isAutoCommit
     * 33      *        true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
     * 34      *        false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
     * 35      * @return SqlSession
     * 36
     */
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}
文件结构:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值