使用getMapper面向接口编程
前面的代码都是使用如下对数据库进行操作:
对方法insert 、delete 、update 和selectList 传入sqlId 来达到调用SQL 语句而对数据库的操作
sqlSession.insert("insertUserinfo","xxx");
sqlSession.delete("deleteById","xxx");
sqlSession.update("updateById","xxx") ;
sqlSession.selectList("selectUserinfo","xxx");I
这种代码是不规范的,规范的写法不是面向sqlld 编程,而是面向接口编程,比sqlid 的方式,使用“接口- SQL 映射”在代码规范上更好。
接口-SQL 映射的对应关系
SQL 映射文件userinfoMapper.xml 中的 namespace 属性值 sqlmapping.UserinfoMapper 代表
该映射对应的就是 mapping 包中的UserinfoMapper接口,
而<insert>标签的 id 属性值 insertUserinfo 就是 UserinfoMapper接口中的public void insertUserinfo ( Userinfouserinfo )方法,<insert> 标签的 parameterType 属性值mapping.Userinfo 就是public void insertUserinfo(Userinfo userinfo)的方法参数类型.
创建Userinfo实体类
public class Userinfo {
private long id;
private String username;
private String password;
private long age;
private Date createTime;
public Userinfo() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
public Date getInsertdate() {
return createTime;
}
public void setInsertdate(Date createTime) {
this.createTime = createTime;
}
}
创建UserinfoMapper 接口
public interface UserinfoMapper {
public void insertUserinfo(Userinfo userinfo);
public List<Userinfo> selectAll();
public Userinfo selectById(long userId);
public void deleteById(long userId);
public void updateById(Userinfo userinfo);
}
SQL 映射文件UserinfoMapper.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="mapping.UserinfoMapper">
<insert id="insertUserinfo" parameterType="entity.Userinfo">
insert into userinfo(username,password,age,createTime)
values(#{username},#{password},#{age},#{createTime})
</insert>
<select id="getAllUserinfo" resultType="entity.Userinfo">
select * from userinfo order
by id asc
</select>
<select id="getUserinfoById" parameterType="long" resultType="entity.Userinfo">
select *
from userinfo where id=#{id}
</select>
<delete id="deleteUserinfoById" parameterType="long">
delete
from userinfo where
id=#{id}
</delete>
<update id="updateUserinfoById" parameterType="entity.Userinfo">
update userinfo set
username=#{username},
password=#{password},
age=#{age},
createTime=#{createTime}
where id=#{id}
</update>
</mapper>
增加记录insertUserinfo的代码
public class InsertUserinfo {
public static void main(String[] args) {
try{
Userinfo userinfo = new Userinfo();
userinfo.setUsername("渡西湖");
userinfo.setPassword("duxihu");
userinfo.setAge(18);
string resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceasStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserinfoMapper userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);
userinfoMapper.insertUserinfo(userinfo);
sqlSession.commit();
sqlSession.close();
System.out.println("createId=" + userinfo.getId());
}catch (IOException e){
e.printStackTrace();
}
}
}
接口UserinfoMapper并不能直接使用, 必须得有接口UserinfoMapper的实现类才可以执行任务。MyBatis 动态地创建出了接口UserinfoMapper的实现类,所以才可以对UserinfoMapper 对象进行赋值, 属于多态关系。
UserinfoMapper userinfoMapper = sqlSession.getMapper(UserinfoMapper.class);
使用tvpeAliases 配置别名
在执行se lect 查询或insert添加的SQL 语句时,都要在parameterType 或resultType 属性中写上完整的实体类路径,路径中需要包含完整的包名 ,这时可以在mybatis-config.xml配置文件中使用<typeAliases>标签来简化
<typeAliases>
<typeAlias type="entity.Userinfo" alias="userinfo" />
</typeAliases>
其中type就是完整名称,alias就是别名,这个别名可以在SQL 映射文件中进行使用,从而简化了配置代码
使用package 批量配置别名
如果实体类的数量较多,可以通过使用<package>标签来解决,在<typeAliases>标签中使用<package>子标签来扫描包中的类而自动创建出类的别名
<typeAliases>
<package name="entity" />
</typeAliases>
如果在不同的包中出现相同实体类名的情况下, 在MyBatis 解析XML 配置文件时就会出现异常信息
使用properties 文件保存数据库信息
可以将连接数据库的信息转移到properties 属性文件中,这样也便于代码的后期维护与管理
更改mybatis-config.xml 配置文件的部分代码如下:
<configuration>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapping/UserinfoMapper.xml" />
</mappers>
</configuration>
添加了配置代码<properties resource="db.properties"></properties>来使用db.properties
src 中创建db.properties 属性文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatisdemo?serverTimezone=UTC&useSSL=false&characterEncoding=utf8
username=test
password=test
与数据源Datasource 有关的操作
1. 配置多个environment 环境
<configuration>
<properties resource="db.properties"></properties>
<environments default="oracle2">
<environment id="oracle1">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${oracle1.driver}" />
<property name="url" value="${oracle1.url}" />
<property name="username" value="${oracle1.username}" />
<property name="password" value="${oracle1.password}" />
</dataSource>
</environment>
<environment id="oracle2">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${oracle2.driver}" />
<property name="url" value="${oracle2.url}" />
<property name="username" value="${oracle2.username}" />
<property name="password" value="${oracle2.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapping/UserinfoMapper.xml" />
</mappers>
</configuration>
配置<environments default=”oracle2”>代码中的default 属性值是oracle2 ,代表要连接的是oracle2 中的配置信息
db.properties代码
oracle1.driver=oracle.jdbc.OracleDriver
oracle1.url=jdbc:oracle:thin:@localhost:1521:orcl
oracle1.username=test
oracle1.password=test
oracle2.driver=oracle.jdbc.OracleDriver
oracle2.url=jdbc:oracle:thin:@localhost:1521:orcl
oracle2.username=test
oracle2.password=errorpassword