Mybatis
一、框架概念:
Java框架,一个软件半成品,简单来说就是一个别人搭好的舞台,你来做表演,说白了Java框架就是封装好方便程序员操作的类,使项目的开发更简单,维护起来也更容易。
而Mybatis框架是一个优秀的java持久层框架,他内部封装了jdbc,开发者只需要关注sql语句本身,其他繁琐的操作框架会替你完成。
二、入门:
1.开发dao:
1.1 原始dao开发模式
编写dao接口,编写dao实现类,存在大量重复代码!
1.2使用mapper代理开发模式(推荐):
1.2.1配置xml:
*SqlMapConfig.xml的配置
*userMapper.xml配置:
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{addrsss});
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
delete from user where id = #{userid}
*jdbc.properties配置:
DriverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
username=root
password=******
initialSize=5
maxActice=10
maxWait=3000
*测试方法:
public class MybatisTest {
private InputStream in;
private SqlSession session;
private Usermapper usermapper;
@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlsessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
usermapper = session.getMapper(Usermapper.class);
}
@After
public void destory()throws Exception{
session.close();;
in.close();
}
@Test
public void findAllTest() throws Exception {
//5.使用代理对象执行方法
List users = usermapper.findAll();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void saveUser(){
User user = new User();
user.setUsername("3241");
user.setBirthday(new Date());
user.setSex("男");
user.setAddrsss("1231241");
usermapper.saveUser(user);
session.commit();
System.out.println(user);
}
@Test
public void updateUser(){
User user = new User();
user.setId(53);
user.setUsername("155");
user.setBirthday(new Date());
user.setSex("男");
user.setAddrsss("544");
usermapper.updateUser(user);
session.commit();
}
@Test
public void deleteUser(){
User user = new User();
usermapper.deleteUser(49);
session.commit();
}
}
1.2.2注意事项:
*我的mysql安装为8.0,所以在url后面要加上 “?useUnicode=true&characterEncoding=utf8”
*主键回填:
一般id是主键,我们在插入信息时也不必主动去设置。数据库会自动增长,但插入成功后我们要得知插入数据的id是多少时,就得设置这2个:
useGeneratedKeys="true" keyProperty="id" 仅能在 或者< update>元素中使用,作用是获取自增主键的id
例:
@Test
public void saveUser(){
User user = new User();
user.setUsername("3241");
user.setBirthday(new Date());
user.setSex("男");
user.setAddrsss("1231241");
usermapper.saveUser(user);
session.commit();
System.out.println(user);
}
没有加上时:打印出来的id为null,反之。
2.连接池
在SqlMapConfig.xml中配置:
1.POOLED:使用数据库连接池
2.UNPOOLED:不使用数据库连接池
3.JNDI
3.动态sql语句
where+if语句:
@Test
public void findUserbyCondition() throws Exception {
User user = new User();
user.setUsername("老王");
//5.使用代理对象执行方法
List users = usermapper.findUserbyCondition(user);
for (User user1 : users) {
System.out.println(user1);
}
}
查询结果:
User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', addrsss='null'}
User{id=46, username='老王', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', addrsss='null'}
where+foreach:
public void findUserbyCondition() throws Exception {
List list = new ArrayList();
list.add(41);
list.add(42);
List users = usermapper.findUserbyCondition(list);
for (User user : users) {
System.out.println(user);
}
}
查询结果:
User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', addrsss='null'}
User{id=42, username='小二王', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', addrsss='null'}
3.映射
一对一:
user类:
public class User {
private String username;
private String sex;
//以下省略get和set、toString方法
order类:
public class Order {
private int id;
private int userid;
private String number;
private User user;
//以下省略get和set、toString方法
OrderMapper.xml:
运行结果:
Order{id=1, userid=1, number='10000', user=User{username='是谁', id=1, sex='男'}}
Order{id=2, userid=5, number='11111', user=User{username='解开了', id=5, sex='男'}}
Order{id=3, userid=2, number='13431', user=User{username='老王', id=2, sex='男'}}
Order{id=4, userid=3, number='131231', user=User{username='哦哦', id=3, sex='女'}}
注意事项:
数据库的order表和user表的id最好不要相同,否则Mabatis会弄混,导致这样结果:
Order{id=1, userid=1, number='10000', user=User{username='是谁', id=1, sex='男'}}
Order{id=5, userid=5, number='11111', user=User{username='解开了', id=5, sex='男'}}
Order{id=2, userid=2, number='13431', user=User{username='老王', id=2, sex='男'}}
Order{id=3, userid=3, number='131231', user=User{username='哦哦', id=3, sex='女'}}
即order的id强制跟user的id相同
一对多:
Class类:
public class Class {
private Integer id;
private String name;
private List students;
}
Student类:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
}
ClassMapper.xml:
三.注解开发
CURD
使用注解开发便不需要mapper.xml这样的配置文件了
*下面是代码:
userMapper:
public interface UserMapper {
@Select("select *from user")
List findAll();
@Insert("insert into user(username,sex) value(#{username},#{sex})")
void SaveUser(User user);
@Update("update user set username=#{username}, sex=#{sex} where id =#{id}")
void updateUser(User user);
@Delete("delete from user where id =#{id}")
void deleteUser(int id);
}
SqlMapConfig相关改动:
一对一:
user表:
id username sex
1 是谁 男
2 老王 男
4 123 男
5 解开了 男
6 王二 女
user:
private int id;
private String username;
private Order order;
getter and setter 方法
toString 方法
order表:
id userid number
1 1 10000
2 5 11111
3 2 13431
4 3 131231
order:
private int oid;
private int userid;
private String number;
OrderMapper:
public interface OrderMapper {
@Select("select *from `order` where userid = #{id} ")
Order findOrderById(int id);
}
Usermapper:
public interface UserMapper {
@Select("select *from user")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "sex",property = "sex"),
@Result(column = "id",property = "order",one = @One(select = "cn.zzz.dao.OrderMapper.findOrderById",fetchType = FetchType.EAGER))
})
List findAll();
}
查询结果:
User{id=1, username='是谁', order=Order{oid=1, userid=1, number='10000', user=null}, sex='男'}
User{id=2, username='老王', order=Order{oid=3, userid=2, number='13431', user=null}, sex='男'}
User{id=4, username='123', order=null, sex='男'}
User{id=5, username='解开了', order=Order{oid=2, userid=5, number='11111', user=null}, sex='男'}
User{id=6, username='王二', order=null, sex='女'}