mybatis的简单使用调用mapper接口

时间:2022-01-31 13:23:57

mybatis 是apache下的一个面向sql编程的半自动化的ORM持久层的框架。特点:面向sql编程,达到高性能的使用目的。

下面是简单使用

现导入jar包,只有mybatis和数据库驱动包(这里用的是mysql的驱动包)是必须的,其余是日志需要的包

mybatis的简单使用调用mapper接口

db.properties配置连接池的配置文件

 jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=12

创建一个mybatis数据库,执行下面的生sql语句插入数据

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('', '王五', null, '', null);
INSERT INTO `user` VALUES ('', '张三', '2014-07-10', '', '北京市');
INSERT INTO `user` VALUES ('', '张小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '张三丰', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '王五', null, null, null);

log4j.properties  日志的配置文件

 ### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdout

SqlMapConfig.xml  是mybatis全局的配置文件

<?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>
<properties resource="db.properties">
</properties>
<typeAliases>
<!-- 单个别名定义 ,后面就可用直接写user,不用写全路径名-->
<!-- <typeAlias type="com.baoyuan.domain.User" alias="user"/> -->
<!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
<package name="com.baoyuan.domain"/>
</typeAliases>
<!--名称随意 -->
<environments default="development">
<!--id必须和上面的一致 -->
<environment id="development">
<!--固定格式JDBC -->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments> <mappers> <!-- 使用mapper接口类路径 注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中-->
<!-- <mapper class="com.baoyuan.mapper.dao.UserMapper"/> --> <!-- 注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。 -->
<package name="com.baoyuan.mapper.dao"/>
</mappers>
</configuration>

创建一个pojo类User类

package com.baoyuan.domain;

import java.util.Date;

public class User {

    private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + "]";
} }

在src目录下建立一个com.baoyuan.mapper.dao的包

在com.baoyuan.mapper.dao创建一个UserMapper.xml的映射文件

Mapper接口开发需要遵循以下规范:

1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。

2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同

3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同

4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

<?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.baoyuan.mapper.dao.UserMapper">
    <!-- Id表示statement的id唯一标识符,resultType表示结果集的类型,parameterType表示形式参数类型 ,如果SqlMapConfig.xml中配置了别名,就可以直接谢别名user,不用再写全路径com.baoyuan.domain.User -->
<select id="findUserById" resultType="com.baoyuan.domain.User" parameterType="int" >
                    <!--#{}大括号类随意写只是表示一个占位符,相当于statment中的"?"  -->
select * from user where id =#{id}
</select>
                    <!--这里返回的类型虽然是list,resultType表示list泛型的类型  -->
<select id="findUserByUsername" resultType="com.baoyuan.domain.User" parameterType="java.lang.String" >
                              <!--这里必须写value,${value}表示拼接字符串,如果用其他会报错,用#{}只是表示占位符,可以在调用时传"%条件%的参数"  -->
select * from user where username like '%${value}%'
</select>
<insert id="saveUser" parameterType="com.baoyuan.domain.User" >
        <!--配置在插入一条数据后返回主键,会自动保存到pojo对象的主键属性中  -->
        <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
            select LAST_INSERT_ID()
            <!--必须是主键自增长 是mysql的函数,返回auto_increment自增列新记录id值 -->
        </selectKey>
        <!-- <selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">
                select uuid()
                需要增加通过select uuid()得到uuid值(前提是用户表中的id必须是字符串类型)
        </selectKey> -->
                                      <!--这里由于 parameterType形式参数的类型是user,所以这里#{}大括号中不能随便写,写的是user的属性 -->
insert INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert>
<delete id="deleteUserById" parameterType="int">
delete from user where id =#{id}
</delete>
<update id="updateUserById" parameterType="com.baoyuan.domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
</mapper>

创建UserMapper的接口

package com.baoyuan.mapper.dao;

import java.util.List;

import com.baoyuan.domain.User;
//类名必须和
public interface UserMapper {
public User findUserById(Integer id);
public List<User> findUserByUsername(String username);
public void saveUser(User user);
public void deleteUserById(Integer id);
public void updateUserById(User user);
}

测试代码

package com.baoyuan.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
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.Before;
import org.junit.Test; import com.baoyuan.domain.User;
import com.baoyuan.mapper.dao.UserMapper; public class TestUserMapper {
private SqlSessionFactory sqlSessionFactory ;
   //表示运行测试代码前执行,给sqlSessionFactory赋值
@Before
public void InitialContext() throws IOException{
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream inputStream=Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
this.sqlSessionFactory=sqlSessionFactory; }
//通过id查询用户
@Test
public void findUserById(){
//获取sqlsession
SqlSession sqlSession=null;
try {
sqlSession = sqlSessionFactory.openSession();
//获取mapper接口代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findUserById(1);
System.out.println(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
//通过用户名模糊查询用户
@Test
public void findUserByUsername(){
//获取sqlsession
SqlSession sqlSession=null;
try {
sqlSession = sqlSessionFactory.openSession();
//获取mapper接口代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findUserByUsername("张");
System.out.println(list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
//保存用户
@Test
public void saveUser(){
//获取sqlsession
SqlSession sqlSession=null;
try {
sqlSession = sqlSessionFactory.openSession();
//获取mapper接口代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user=new User();
user.setUsername("李四");
user.setBirthday(new Date());
user.setSex("1");
user.setAddress("深圳");
System.out.println(user.getId());
userMapper.saveUser(user);
sqlSession.commit();
        System.out.println(user.getId());
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
//更新用户
@Test
public void updateUserById(){
//获取sqlsession
SqlSession sqlSession=null;
try {
sqlSession = sqlSessionFactory.openSession();
//获取mapper接口代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user=new User();
user.setId(30);
user.setUsername("李四");
user.setBirthday(new Date());
user.setSex("1");
user.setAddress("深圳");
userMapper.updateUserById(user);;
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
//删除用户
@Test
public void deleteUserById(){
//获取sqlsession
SqlSession sqlSession=null;
try {
sqlSession = sqlSessionFactory.openSession();
//获取mapper接口代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUserById(30);;
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
}