Mybatis框架:
需要配置文件
- 核心配置文件(只能有1个)
- 映射配置文件(允许有多个)
相关API
- SqlSessionFactory //会话工厂(创建:SqlSession对象)
- SqlSession //会话对象 (底层封装了Connection对象) //和数据库交互
- 底层使用:Executor(执行器。 执行sql语句)
- 执行SQL语句时:有占位符、有SQL执行结果
- 占位符:赋值(输入参数)
- SQL执行结果: 取值(输出参数)
开发mybatis程序:
- 配置文件
- 数据库连接配置
- SQL语句
- API:SqlSessionFactory、SqlSession
在Mybatis技术中有一个概念:ORM映射
-
O:就是对象(Java中类的对象)
-
R:关系(关系型数据库)
-
M:映射(把Java类和数据表建立对应关系)
数据表: tb_user 字段: id、username、password、age 类: User 成员方法:id、name、password、age O: User类的对象 R: tb_user表
-
类名 <==> 表名
-
成员变量 <==> 字段名
-
对象 <==> 一行记录
结论:Mybatis就是基于ORM机制一种框架技术
- Mybatis有两种针对ORM映射的实现方式:
- XML配置文件
- 注解
maven的mybatis入门案例:
-
创建maven工程
-
导入相关依赖:mybatis、mysql
-
在src/main/resource目录下,创建:mybatis核心配置文件
-
核心配置文件名可以自定义。建议:mybatis-config.xml
-
配置1:和数据库连接相关的参数
-
配置2:关联映射文件
-
数据库表
create table user
(
id int primary key auto_increment,
username varchar(20) not null,
birthday date,
sex char(1) default '男',
address varchar(50)
);
insert into user
values (null, '孙悟空', '1980-10-24', '男', '花果山水帘洞');
insert into user
values (null, '白骨精', '1992-11-12', '女', '白虎岭白骨洞');
insert into user
values (null, '猪八戒', '1983-05-20', '男', '福临山云栈洞');
insert into user
values (null, '蜘蛛精', '1995-03-22', '女', '盤丝洞');
resources文件
jdbc.properties
# 数据库配置文件
# 格式: key=value
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/db3
jdbc.username=root
jdbc.password=1234
mybatis-config.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>
<!--1、properties-->
<properties resource="jdbc.properties"></properties>
<!--2、settings-->
<settings>
<!--开启驼峰自动映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--3、typeAliases-->
<typeAliases>
<!--<typeAlias type="com.heima.mybatis.pojo.User" alias="User"/>-->
<package name="com.heima.mybatis.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<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>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
UserMapper.xml
<?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">
<!--UserMapper接口的文件位置-->
<mapper namespace="com.itheima.Dome.helloWorld.UserMapper">
<!--根据id查询:selectxiyouji,接口中必须要有selectxiyouji这个方法-->
<select id="selectxiyouji" resultType="com.itheima.Dome.helloWorld.User">
select id, username, birthday, sex, address from user
</select>
</mapper>
com.itheima.Dome.helloWorld文件
MybatisTset
package com.itheima.Dome.helloWorld;
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.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTset {
@Test
public void Test01() throws IOException {
//1.创建Sq1SessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.得到会话工厂Sq1SessionFactory类
SqlSessionFactory build = sqlSessionFactoryBuilder.build(MybatisTset.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
//3.得到SqlSession对象(sqlSession相当于数据库连接)
SqlSession sqlSession = build.openSession();
//4.通过SqlSession对象得到Mapper接口的代理对象(实现类)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.Mapper接口的代理对象执行数据库的查询操作
List<User> user = mapper.selectxiyouji();
for (User user1 : user) {
System.out.println(user);
}
// 6.关闭Sq1Session
sqlSession.close();
}
}
User
package com.itheima.Dome.helloWorld;
import java.util.Date;
public class User {
private Integer id;//为了保证java成员变量中也能存储null,使用包装类Integer
private String username;
private Date birthday;
private String sex;
private String address;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + 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;
}
public User(Integer id, String username, Date birthday, String sex, String address) {
this.id = id;
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
public User() {
}
}
UserMapper(接口)
package com.itheima.Dome.helloWorld;
import java.util.List;
public interface UserMapper {
//查询所有用户信息
public abstract List<User> selectxiyouji();
}
java的mybatis入门案例
数据库表
create table user
(
id int primary key auto_increment,
username varchar(20) not null,
birthday date,
sex char(1) default '男',
address varchar(50)
);
insert into user
values (null, '孙悟空', '1980-10-24', '男', '花果山水帘洞');
insert into user
values (null, '白骨精', '1992-11-12', '女', '白虎岭白骨洞');
insert into user
values (null, '猪八戒', '1983-05-20', '男', '福临山云栈洞');
insert into user
values (null, '蜘蛛精', '1995-03-22', '女', '盤丝洞');
idea导包
UserMapper(接口)
package com.itheima.dao;
import com.itheima.entity.User;
import java.util.List;
public interface UserMapper {
//查询所有用户的方法
public abstract List<User> findAllUsers();
}
User
package com.itheima.entity;
import java.util.Date;
//实体类,User对象是来保存数据库中的数据
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + 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;
}
public User(Integer id, String username, Date birthday, String sex, String address) {
this.id = id;
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
public User() {
}
}
TestMyBatis
package com.itheima.Test;
import com.itheima.dao.UserMapper;
import com.itheima.entity.User;
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 java.util.List;
public class TestMyBatis {
@Test
public void fangfa(){
//1.创建Sq1SessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.得到会话工厂Sq1SessionFactory类
SqlSessionFactory build = sqlSessionFactoryBuilder.build(TestMyBatis.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
//3.得到SqlSession对象
SqlSession sqlSession = build.openSession();
//4.通过SqlSession对象得到Mapper接口的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.Mapper接口的代理对象执行数据库的查询操作
List<User> allUsers = mapper.findAllUsers();
//6.关闭Sq1Session
sqlSession.close();
for (User allUser : allUsers) {
System.out.println(allUser);
}
}
}
UserMapper.xml
<?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.itheima.dao.UserMapper">
<select id="findAllUsers" resultType="com.itheima.entity.User">
select id, username, birthday, sex, address from user
</select>
</mapper>
log4j.properties
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
mybatis-config.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>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--1.3配置连接池需要的参数-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/db3"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/itheima/dao/UserMapper.xml"/>
</mappers>
</configuration>
Mybatis增删改查
根据用户id查询用户
增加(Create )
读取(Retrieve)
更新(Update)
删除(Delete)
my Batis 三种开发方式
接口代理的开发方式(重点)
根据用户id来查询用户信息
1.在接口中创建方法:(通过用户id来查询用户信息)
//根据id查询信息
public abstract List<User> findUserById();
package com.itheima.Dome.helloWorld;
import java.util.List;
public interface UserMapper {
//查询所有用户信息
public abstract List<User> findAllUsers();
//根据id查询信息
public abstract List<User> findUserById(int uid);
}
2.配置UserMapper.xml(设置sql通过id查询用户信息语句)
<!--select标签:配置查询的SQL语句
id:接口中的方法名
parameter:数据类型
resultType:方法返回值类型,如果方法返回值类型是集合,不需要写集合,只要写里面的类型
主体内容:SQL语句
#{参数名}:先试用?占位,后取参数的值赋给
-->
<select id="findUserById" parameterType="int" resultType="com.itheima.Dome.helloWorld.User">
select*from user where id=#{uid} ;
</select>
3.编写测试类
@Test
public void Test02() throws IOException {
//1.创建Sq1SessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.得到会话工厂Sq1SessionFactory类
SqlSessionFactory build = sqlSessionFactoryBuilder.build(MybatisTset.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
//3.得到SqlSession对象(sqlSession相当于数据库连接)
SqlSession sqlSession = build.openSession();
//4.通过SqlSession对象得到Mapper接口的代理对象(实现类)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.Mapper接口的代理对象执行数据库的查询操作
List<User> user =mapper.findUserById(1);
System.out.println(user);
//6.关闭锁
sqlSession.close();
}
根据用户id来删除用户信息
1.在接口中创建方法:(通过用户id来删除用户信息)
//根据id删除用户信息
//返回值void既可以,如果想知道删除几行,返回值int
public abstract int deleteUser(int did);
2.配置UserMapper.xml(设置sql通过id删除用户信息语句)
<!--delete标签:配置查询的SQL语句
id:接口中的方法名
parameter:数据类型
主体内容:SQL语句
增删改没有resultType返回值类型配置
#{参数名}:先试用?占位,后取参数的值赋给
-->
<delete id="deleteUser" parameterType="int" >
delete from user where id=#{did};
</delete>
3.编写测试类
@Test//通过id删除用户id
public void Test03() throws IOException {
//1.创建Sq1SessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.得到会话工厂Sq1SessionFactory类
SqlSessionFactory build = sqlSessionFactoryBuilder.build(MybatisTset.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
//3.得到SqlSession对象(sqlSession相当于数据库连接)(自动提交事务:每句SQL都自动提交一下)
SqlSession sqlSession = build.openSession(true);
//4.通过SqlSession对象得到Mapper接口的代理对象(实现类)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.Mapper接口的代理对象执行数据库的查询操作
int index =mapper.deleteUser(1);
//手动提交事务
//sqlSession.commit();
System.out.println("受影响行数:"+index);
//6.关闭锁
sqlSession.close();
}
根据用户id来修改用户信息
1.在接口中创建方法:(通过用户id来修改用户信息)
//修改用户方法,要修改的数据都放在User对象里面
public abstract int updateUser(User user);
2.配置UserMapper.xml(设置sql通过id修改用户信息语句)
<!--update标签:配置修改的SQL语句
parameterType参数是自定义类型:#{成员变量名},就可以取出变量值
-->
<update id="updateUser" parameterType="com.itheima.Dome.helloWorld.User">
<!--根据用户id修改参数-->
UPDATE user SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id};
</update>
3.编写测试类
@Test//修改用户信息
public void Test04() throws IOException {
//1.创建Sq1SessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.得到会话工厂Sq1SessionFactory类
SqlSessionFactory build = sqlSessionFactoryBuilder.build(MybatisTset.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
//3.得到SqlSession对象(sqlSession相当于数据库连接)(自动提交事务)
SqlSession sqlSession = build.openSession();
//4.通过SqlSession对象得到Mapper接口的代理对象(实现类)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//5.Mapper接口的代理对象执行数据库的查询操作
User user = new User(1, "齐天大圣2", Date.valueOf("1988-09-09"), "公", "北京市");
int index=mapper.updateUser(user);
System.out.println("受影响行数:"+index);
//6.关闭锁
sqlSession.close();
}