mybatis(一)—-实现crud操作

一、mybatis环境搭建

1、所需资源

a、mybatis-3.2.7.zip下的jar包

b、Eclipse开发集成工具

2、建Java Project,导包

3、建立数据库和表

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`),
UNIQUE KEY `id` USING BTREE (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4、po类User.java和供查询的UserQuery.java

package top.einino.po;

import java.util.Date;

public class User {
public Integer id;
public String username;
public String gender;
public Date birthday;
public 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
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 + “, gender=”
+ gender + “, birthday=” + birthday + “, address=” + address
+ “]”;
}

}

package top.einino.po;

import java.util.ArrayList;
import java.util.List;

public class UserQuery extends User{
//查询字段 字符串拼接形式,例”username,sex”
private String fields;
//定义排序集合
private List orderBy = new ArrayList();
//分页设置,起始行
private Integer startRow;
//每页行数,初定10
private int rows = 10;

public String getFields() {
return fields;
}
public void setFields(String fields) {
this.fields = fields;
}

public List getOrderBy() {
return orderBy;
}
public void setOrderBy(List orderBy) {
this.orderBy = orderBy;
}
public Integer getStartRow() {
return startRow;
}
public void setStartRow(Integer startRow) {
this.startRow = startRow;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}

private class OrderFields{
//排序字段
private String field;
//排序规则
private String order;

public OrderFields(String field, String order) {
super();
this.field = field;
this.order = order;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}

}
//添加排序
public void addOrder(String field, String order) {
orderBy.add(new OrderFields(field, order));
}

}

 

5、新建Source Folder类型的文件夹config,加入mybatis的主要配置文件:SqlMapConfig.xml

内容如下:


PUBLIC “-//mybatis.org//DTD Config 3.0//EN”
“http://mybatis.org/dtd/mybatis-3-config.dtd”>


db.properties“>

<typeAliases>

typeAliases>

development“>

development“>

JDBC“>
POOLED“>




<mappers>


mappers>

6、加入数据库资源文件:db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=自己的用户名
jdbc.password=自己的密码

二、实现crud操作

7、写UserMapper.xml


PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN”
“http://mybatis.org/dtd/mybatis-3-mapper.dtd”>
top.einino.mapper.UserMapper“>


usermap“>







selectFields“>
select

${fields}


id,username,gender,birthday,address

from user


condition“>


and id = #{id}


and username like  ‘%${username}%’


and gender = #{gender}


and birthday = #{birthday}


and address = #{address}




order“>
0″>
order by

${ob.field}  ${ob.order}



limitPage“>

limit #{startRow}, #{rows}



saveUser” parameterType=”user”>

select LAST_INSERT_ID()

insert into user(username,
sex,
birthday,
address)
values
(#{username},
#{gender},
#{birthday}, #{address})





deleteUserById” parameterType=”java.lang.Integer”>
delete from user
where id = #{id}


deleteUserByIds” parameterType=”Integer[]”>
delete from user
where
id in

#{id}


updateUser” parameterType=”user”>
update user set username = #{username},
sex = #{gender},
birthday = #{birthday},
address = #{address}
where id = #{id}

6、写UserMapper.java

package top.einino.mapper;

import java.util.List;

import top.einino.po.User;
import top.einino.po.UserQuery;

public interface UserMapper {
//添加用户
public void saveUser(User user);
//通过id查找用户
public User findUserById(Integer id);
//通过查询条件查询id
public List findUserListByCondition(UserQuery userQuery);
//通过id删除用户
public void deleteUserById(Integer id);
//通过id数组删除用户
public void deleteUserByIds(Integer[] ids);
//修改用户
public void updateUser(User user);
}

7、测试类

package top.einino.junit;

import java.io.IOException;
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 top.einino.mapper.UserMapper;
import top.einino.po.User;
import top.einino.po.UserQuery;

public class TestUserMapper {

 

 private SqlSessionFactory sqlSessionFactory;

@Before
public void setSqlSessionFactory() throws IOException{

//通过配置文件获得sqlSessionFactory
sqlSessionFactory = new  SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(“SqlMapConfig.xml”));

}
//测试添加用户
@Test
public void saveUser(){

User user = new User();
user.setUsername(“einino”);
user.setGender(“男”);
user.setBirthday(new Date());
user.setAddress(“广州”);
//获得sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获得接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法
mapper.saveUser(user);
//测试是否返回id
System.out.println(user.getId());
//提交
sqlSession.commit();
//关闭
sqlSession.close();

}

//测试通过id查找用户
@Test
public void findUserById(){

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.findUserById(1);
System.out.println(user);
sqlSession.close();

}

//通过查询条件,查询user集合
@Test
public void findUserListByCondition(){

UserQuery userQuery = new UserQuery();
userQuery.setFields(“id,username,sex”);
// userQuery.setUsername(“张”);
userQuery.addOrder(“id”, “asc”);
userQuery.setStartRow(10);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List users = mapper.findUserListByCondition(userQuery);
for(User user : users){

System.out.println(user);

}
sqlSession.close();

}
//通过id删除用户
@Test
public void deleteUserById(){

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUserById(34);
sqlSession.commit();
sqlSession.close();

}
//通过数组id删除用户
@Test
public void deleteUserByIds(){

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Integer[] ids = {35, 36, 37};
mapper.deleteUserByIds(ids);
sqlSession.commit();
sqlSession.close();

}
//更新用户
@Test
public void updateUser(){

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(26);
user.setUsername(“bingo”);
user.setAddress(“广州”);
user.setGender(“男”);
user.setBirthday(new Date());
mapper.updateUser(user);
sqlSession.commit();
sqlSession.close();

}

}

三、小结

该博文主要搭建了mybatis的环境,以及实现增删查改操作,并且查询功能很丰富。

如果有疑问或者对该博文有何看法或建议或有问题的,欢迎评论,恳请指正!

你可能感兴趣的:(mybatis)