create database mybatis_db;
use mybatis_db;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'老王','2018-02-27 17:47:08','男','北京'),(2,'熊大','2018-03-02 15:09:37','女','上海'),(3,'熊二','2018-03-04 11:34:34','女','深圳'),(4,'光头强','2018-03-04 12:04:06','男','广州');
org.mybatis
mybatis
3.4.5
mysql
mysql-connector-java
5.1.6
junit
junit
4.10
test
log4j
log4j
1.2.17
log4j.properties配置文件
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
3.编写User的实现类,属性尽量使用包装类型,具体的代码如下
package com.qcby.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private static final long serialVersionUID = 525400707336671154L;
private Integer id;
private String username;
private Date birthday;
private String sex;
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
4.编写UserMapper的接口和方法(相当于UserDao接口)
package com.qcby.mapper;
import com.qcby.domain.User;
import java.util.List;
public interface UserMapper {
/**
* 查询所有的用户
* @return
*/
public List findAll();
}
5.在resources目录下,创建mappers文件夹。编写UserMapper.xml的配置文件,导入约束文件。
6.编写主配置文件,在resources目录下创建SqlMapConfig.xml的配置文件(其实名称可以任意),导入对应的约束,编写主配置文件。
7.编写测试方法
package com.qcby.test;
import com.qcby.domain.User;
import com.qcby.mapper.UserMapper;
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 java.io.InputStream;
import java.util.List;
public class UserTest {
/**
* 测试查询所有的方法
* @throws Exception
*/
@Test
public void testFindAll() throws Exception {
// 加载主配置文件,目的是构建SqlSessionFactory的对象
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 使用SqlSessionFactory工厂对象创建SqlSession对象
SqlSession session = factory.openSession();
// 通过session创建UserMapper接口的代理对象
UserMapper mapper = session.getMapper(UserMapper.class);
// // 调用查询所有的方法
// List list = mapper.findAll();
// // 遍历集合
// for (User user : list) {
// System.out.println(user);
// }
// //根据id查询
// User user = mapper.findById(1);
// System.out.println(user);
//插入数据
User user = new User();
user.setUsername("美美");
user.setBirthday(new Date());
user.setSex("男");
user.setAddress("顺义");
mapper.insert(user);
session.commit();
// 释放资源
session.close();
in.close();
}
@Test
public void run2() throws Exception {
// 加载配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 构建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取到session对象
SqlSession session = factory.openSession();
// // 查询所有的数据
// List list = session.selectList("com.qcby.mapper.UserMapper.findAll");
// // 变量集合
// for (User user : list) {
// System.out.println(user);
// }
// //根据id查询数据
// User user = session.selectOne("com.qcby.mapper.UserMapper.findById",1);
// System.out.println(user);
//插入数据
User user = new User();
user.setUsername("曹操");
user.setBirthday(new Date());
user.setSex("女");
user.setAddress("南昌");
int id = session.insert("com.qcby.mapper.UserMapper.insert",user);
session.commit();
System.out.println(id);
// 关闭资源
session.close();
inputStream.close();
}
}
package com.qcby.mapper;
import com.qcby.domain.User;
import java.util.List;
public interface UserMapper {
/**
* 查询所有的用户
* @return
*/
public List findAll();
public User findById(Integer userId);
public void insert(User user);
public void update(User user);
public void delete(Integer userId);
public List findByName(String username);
public Integer findByCount();
}
3.UserMapper.xml的配置文件代码
/*
keyProperty表示要返回的属性名称
order取值AFTER表示插入数据后的行为
resultType表示返回值的类型
select last_insert_id(): 这是MySQL的函数,用于获取最后一个插入的行的ID。
*/
select last_insert_id();
insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
update user set username = #{username},birthday = #{birthday},sex = #{sex},address=#{address} where id = #{id}
delete from user where id = #{id}
4.TestDemo的代码
package com.qcby.test;
import com.qcby.domain.User;
import com.qcby.mapper.UserMapper;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class TestDemo {
private InputStream in;
private SqlSession session;
private UserMapper mapper;
@Before
public void init() throws Exception {
// 加载配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建工厂对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建Session对象
session = factory.openSession();
// 获取到代理对象
mapper = session.getMapper(UserMapper.class);
}
@After
public void destory() throws IOException {
in.close();
session.close();
}
/**
* 测试查询所有的方法
* @throws Exception
*/
@Test
public void testFindAll() throws Exception {
List list = mapper.findAll();
// 遍历
for (User user : list) {
System.out.println(user);
}
in.close();
}
@Test
public void testFindById() throws Exception {
User user = mapper.findById(4);
System.out.println(user);
in.close();
}
@Test
public void testInsert() throws Exception {
User user = new User();
user.setUsername("美美");
user.setBirthday(new Date());
user.setSex("男");
user.setAddress("顺义");
mapper.insert(user);
session.commit();
System.out.println(user.getId());
}
@Test
public void testUpdate() throws Exception {
User user = mapper.findById(41);
user.setUsername("小凤");
mapper.update(user);
session.commit();
}
@Test
public void testDelete() throws Exception {
mapper.delete(48);
session.commit();
}
// 第一种
@Test
public void testFindByName1() throws Exception {
List list = mapper.findByName("%王%");
for (User user : list) {
System.out.println(user);
}
}
// 第二种
@Test
public void testFindByName2() throws Exception {
List list = mapper.findByName("王");
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testFindByCount() throws Exception {
Integer count = mapper.findByCount();
System.out.println("总记录数:"+count);
}
}
通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。
通过$可以将传入的内容拼接在中且不进行类型转换,${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。
简单的写法:java.lang.Integer --> int integer Int Integer 都可以,框架提供简写的方式。
2.POJO(JavaBean实体类)对象类型,默认是不能简写,可以配置。User对象
3.POJO包装对象类型 包含更多的实体类
package com.qcby.domain;
import javax.management.relation.Role;
import java.io.Serializable;
public class QueryVo implements Serializable {
// 自己属性
private String name;
// user属性
private User user;
// role属性
private Role role;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
// 测试包装类查询
public List findByVo(QueryVo vo);
//测试代码
@Test
public void testFindByVo() throws Exception {
QueryVo queryVo = new QueryVo();
User user = new User();
user.setUsername("花花");
queryVo.setUser(user);
List list = mapper.findByVo(queryVo);
for (User user1 : list) {
System.out.println(user1);
}
}
2.返回POJO数据类型 返回User对象类型
3.resultMap结果类型
resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。 如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。 resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
2.在项目中定义jdbc.properties属性文件,存储数据库相关的信息,统一管理
1.jdbc.properties属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
2.SqlMapConfig.xml的配置文件
2.UserMapper.xml的配置文件使用别名