MyBatis研习录(06)——基于注解的增删改查操作


C语言自学完备手册(33篇)

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

MySQL数据库实操教程(35篇图文版)

推翻自己和过往——自定义View系列教程(10篇)

走出思维困境,踏上精进之路——Android开发进阶精华录

讲给Android程序员看的前端系列教程(40集免费视频教程+源码)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

除了之前的DAO和Mapper接口方式以外,MyBatis还支持使用注解对数据库进行增删改查操作。该方式特点如下:

  • 1、不用再编写xxxMapper.xml映射文件。利用注解替换原在xxxMapper.xml中的操作。
  • 2、保留原xxxMapper.java接口并在mybatis-config.xml中利用class配置mapper
  • 3、注解方式适用于简单的增删改查操作,不宜复杂操作
  • 4、在同一项目中注解方式可以和xml方式混合使用

数据准备

创建数据库mybatisDatabase和表user

DROP DATABASE IF EXISTS mybatisDatabase;
CREATE DATABASE mybatisDatabase;
use mybatisDatabase;
CREATE TABLE user(
  id INT primary key auto_increment,
  username VARCHAR(50),
  password VARCHAR(50),
  gender VARCHAR(10)
);

INSERT INTO user(username,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(username,password,gender) VALUES("momo","234567","female");
INSERT INTO user(username,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(username,password,gender) VALUES("pepe","456123","female");

SELECT * FROM user;

搭建开发环境

创建普通的Java工程,结构如下:
在这里插入图片描述

User

package cn.com.pojo;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User {
	private Integer id;
	private String username;
	private String password;
	private String gender;
	public User() {
		
	}

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

	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;
	}

	public String getPassword() {
		return password;
	}

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

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

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

UserMapper

package cn.com.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserMapper {
	
	@Delete(value="delete from user where id=#{id}")
	public int deleteUserById(Integer id);
	
	@Update(value="update user set username=#{username},password=#{password},gender=#{gender} where id=#{id}")
	public int updateUser(User user);
	
	@Select(value="select id,username,password,gender from user where id = #{id}")
	public User queryUserById(Integer id);
	
	@Select(value="select id,username,password,gender from user")
	public List<User> queryAllUser();
	
	//@Insert(value="insert into user(username,password,gender) values (#{username},#{password},#{gender})")
	//public int insertUser(User user);
	
	@SelectKey(statement="select last_insert_id()",before=false,keyProperty="id",resultType=Integer.class)
	@Insert(value="insert into user(username,password,gender) values (#{username},#{password},#{gender})")
	public int insertUser(User user);
}

要点概述:

1、在org.apache.ibatis.annotations中提供了@Insert、@Delete、@Update、@Selectd等注解用于增删改查。

2、当注解只有一个属性时可省略value,即:

@Select(value="select id,username,password,gender from user where id = #{id}")
public User queryUserById(Integer id);

可以简写为:

@Select("select id,username,password,gender from user where id = #{id}")
public User queryUserById(Integer id);

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>
  <!-- 配置数据源 -->
  <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/mybatisDatabase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 配置mapper -->
  <mappers>
    <mapper class="cn.com.mapper.UserMapper"/>
  </mappers>
  
</configuration>

MybatisTest

package cn.com.test;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
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 cn.com.mapper.UserMapper;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class MybatisTest {

	static SqlSessionFactory sqlSessionFactory = null;

	public static SqlSessionFactory getSqlSessionFactory() {
		try {
			if (sqlSessionFactory == null) {
				InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
			}
			return sqlSessionFactory;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {

		}
		return null;
	}

	@Test
	public void testQueryUserById() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User user = userMapper.queryUserById(1);
		System.out.println(user);
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testQueryAllUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryAllUser();
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testDeleteUserById() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		int result = userMapper.deleteUserById(1);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testUpdateUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(2, "klkl", "123543", "male");
		//利用SqlSession执行数据操作
		int result = userMapper.updateUser(user);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testInsertUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(null, "gugu", "123456", "female");
		//利用SqlSession执行数据操作
		int result = userMapper.insertUser(user);
		System.out.println("result=" + result);
		System.out.println(user);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

}

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
发布了1019 篇原创文章 · 获赞 1913 · 访问量 233万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览