什么是 MyBatis ?
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
教程链接
https://mybatis.github.io/mybatis-3/zh/index.html
第一个helloworld程序源代码
①导入jar包
mybatis-3.2.8.jar
mysql-connector-java-5.1.18-bin.jar
②配置mybatis的配置文件Configuration.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>
<typeAliases>
<typeAlias alias="User" type="com.oracle.pojo.User"/>
</typeAliases>
<!--environments 可以填两种值
development:开发者模式
work:工作模式
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--导入实体类的映射文件-->
<mappers>
<mapper resource="com/oracle/pojo/User.xml"/>
</mappers>
</configuration>
③实体类
package com.oracle.pojo;
public class User {
private int id;
private String userName;
private String userAge;
private String userAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userAge="
+ userAge + ", userAddress=" + userAddress + "]";
}
}
④实体类的配置文件User.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.oracle.pojo.UserMapper">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
</mapper>
⑤测试类
package com.oracle.test;
import java.io.Reader;
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 com.oracle.pojo.User;
public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static{
try{
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSessionFactory getSession(){
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
//"com.oracle.pojo.UserMapper.selectUserByID"是根据实体类的配置文件写的,com.oracle.pojo.UserMapper是配置文件的namespace,selectUserByID是select的id
User user = (User) session.selectOne("com.oracle.pojo.UserMapper.selectUserByID", 1);
System.out.println(user);
} finally {
session.close();
}
}
}
基于xml实现crud
1). 定义sql 映射xml 文件:
<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User">
insert into users(name, age) values(#{name}, #{age});
</insert>
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="com.atguigu.ibatis.bean.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
<select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User">
select * from users where id=#{id}
</select>
<select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User">
select * from users
</select>
2). 在config.xml 中注册这个映射文件
<mapper resource="net/lamp/java/ibatis/bean/userMapper.xml"/>
3). 在dao 中调用:
/*//增
int count = session.insert("com.oracle.pojo.UserMapper.addUser", new User(-1,"kkk","12","nnnn"));
System.out.println(count);*/
/*改
* int count = session.update("com.oracle.pojo.UserMapper.updateUser", new User(3, "kkk2222", "30", "mmmmmm"));
System.out.println(count);*/
/*删
* session.delete("com.oracle.pojo.UserMapper.deleteUser", 3);*/
/*获取所有
* List<User> users = session.selectList("com.oracle.pojo.UserMapper.getAllUser");
System.out.println(users);*/
/*获取一个
* User user = (User) session.selectOne("com.oracle.pojo.UserMapper.selectUserByID", 1);
System.out.println(user);*/
基于注解实现crud
1). 定义sql 映射的接口
package com.oracle.pojo;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface UserMapperImp {
@Insert("insert into user(userName,userAge,userAddress) values (#{userName},#{userAge},#{userAddress})")
public int add(User user);
@Delete("delete from user where id = #{id}")
public void delete(int id);
@Update("update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}")
public void update(User user);
@Select("select * from user")
public List<User> getAll();
@Select("select * from user where id = #{id}")
public User getOne(int id);
}
2). 在config 中注册这个映射接口
<mapper class="com.atguigu.ibatis.crud.ano.UserMapperImp"/>
3). 在dao 类中调用
//--------基于注解---------
UserMapperImp mapper = session.getMapper(UserMapperImp.class);
//mapper.add(new User(-1, "bb", "22", "cc"));
//mapper.delete(4);
//mapper.update(new User(5, "bbbb", "22", "cc"));
/*List<User> users = mapper.getAll();
System.out.println(users);*/
User user = mapper.getOne(1);
System.out.println(user);
几个可以优化的地方
连接数据库的配置单独放在一个properties 文件中
在配置文件中
<properties resource="db.properties"/>
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
为实体类定义别名,简化sql 映射xml 文件中的引用
<typeAliases>
<typeAlias type="com.atguigu.ibatis.bean.User" alias="User"/>
</typeAliases>
可以在src 下加入log4j 的配置文件,打印日志信息
1. 添加jar:
log4j-1.2.16.jar
2.配置log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>