导包
准备POJO已经数据库表
UserPOJO
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
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 + "]";
}
}
数据库表
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;
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);
创建sqlMapConfig.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>
<properties resource="jdbc.properties"></properties>
<typeAliases>
<typeAlias type="com.itheima.pojo.User" alias="User" />
</typeAliases>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url"
value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- map文件的位置 -->
<mappers>
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=你的数据库密码
UserMapper.xml文件(编写sql代码的文件)
<?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">
<!-- namespace后面是动态代理的接口位置 -->
<mapper namespace="com.itheima.mapper.UserMapper">
<!-- 自动resultType映射要求表中属性与数据库属性对应 -->
<select id="findUserByID" parameterType="Integer" resultType="User">
select * from user where id = #{v}
</select>
<!--
而的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而%{}穿入值,sql解析时,参数是不带引号的。
-->
<select id="findUserByUsername" parameterType="String" resultType="com.itheima.pojo.User">
select * from user where username like '%${value}%'
</select>
<insert id="InsertUser" parameterType="com.itheima.pojo.User" >
<selectKey keyProperty="id" order="AFTER" resultType="Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})
</insert>
<update id="UpdateUserByID" parameterType="com.itheima.pojo.User">
update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address}
where id = #{id}
</update>
<delete id="DeleteUserByID" parameterType="Integer">
delete from user where id = #{id}
</delete>
</mapper>
编写测试类
public class MybatisFirstTes {
@Test
//通过用户ID查询用户
public void findUserByID() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
User user = sqlSession.selectOne("test.findUserByID", 10);
System.out.println(user);
}
@Test
//通过用户名称模糊查询用户
public void testfindUserByUsername() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
List<Object> list = sqlSession.selectList("test.findUserByUsername","王");
for (Object user : list) {
System.out.println(user);
}
}
@Test
//保存用户
public void testInsertUser() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
User user = new User();
user.setAddress("深圳");
user.setBirthday(new Date());
user.setSex("1");
user.setUsername("独孤求败");
int insert = sqlSession.insert("test.InsertUser",user);
//需要自己提交事务
sqlSession.commit();
System.out.println(user.getId());
}
@Test
//更新用户
public void testUpdateUserByID() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
User user = new User();
user.setId(29);
user.setAddress("深圳");
user.setBirthday(new Date());
user.setSex("1");
user.setUsername("风清扬");
int insert = sqlSession.insert("test.UpdateUserByID",user);
//需要自己提交事务
sqlSession.commit();
}
@Test
//删除用户
public void testDeleteUserByID() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
int insert = sqlSession.insert("test.DeleteUserByID",29);
//需要自己提交事务
sqlSession.commit();
}
}
动态代理开发
public interface UserMapper {
//遵循4个原则
//接口方法名等于User.xml文件的mapper中的id名字
//返回值类型User.xml文件的mapper中的返回值类型一致
//方法的入参User.xml文件的mapper中的入参要一致
//在User.xml文件的namespace写上这个接口的路径名
public User findUserByID(Integer id);
}
测试
@Test
public void test() throws IOException{
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建一个SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建Sqlession
SqlSession sqlSession = sqlSessionFactory.openSession();
//SqlSession帮我生成一个实现类,给接口就可以了
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User findUserByID = mapper.findUserByID(1);
System.out.println(findUserByID);
}
}
sqlMapConfig.xml的properties属性(引入数据库的资料)
<properties resource="jdbc.properties"></properties>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=你的数据库密码
sqlMapContext之别名
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
这样配置在UserMapper.xml中就不用写完整路径了
<select id="findUserByID" parameterType="Integer" resultType="User">
sqlMapContext之Mapper设置
<mappers>
<package name="com.itheima.mapper"/>
</mappers>
注册指定包下的所有mapper接口 如: 注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。