Mybatis入门
来源:程序员人生 发布时间:2015-04-23 08:24:26 阅读次数:3556次
1、MyBatis介绍
MyBatis是支持普通SQL查询,存储进程和高级映照的优秀持久层框架。MyBatis消除几近所有的JDBC代码和参数的手工设置和对结果集的检索封装。MyBatis可使用简单的XML或注解用于配置和原始映照,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映照成数据库中的记录。
Mybatis⑶.1.1下载地址:http://download.csdn.net/detail/huhui_bj/8575253
2、快速入门
2.1 准备
首先需要添加两个jar包,1个是mybatis⑶.1.1.jar,1个是mysql-connector-java⑸.1.7-bin.jar。然后在MySQL中建立数据库和数据表:
create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('Tom', 12);
INSERT INTO users(NAME, age) VALUES('Jack', 11);
2.2 添加Mybatis的配置文件conf.xml
<?xml version="1.0" encoding="UTF⑻"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis⑶-config.dtd">
<configuration>
<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://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
2.3 定义表所对应的实体类
public class User {
private int id;
private String name;
private int age;
//get,set方法
}
2.4 定义操作users表的SQL映照文件userMapper.xml
<?xml version="1.0" encoding="UTF⑻" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis⑶-mapper.dtd">
<mapper namespace="com.atguigu.mybatis_test.test1.userMapper">
<select id="getUser" parameterType="int"
resultType="com.atguigu.mybatis_test.test1.User">
select * from users where id=#{id}
</select>
</mapper>
2.5 在conf.xml文件中注册userMapper.xml文件
<mappers>
<mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/>
</mappers>
2.6 编写测试代码
String resource = "conf.xml";
//加载mybatis的配置文件(它也加载关联的映照文件)
Reader reader = Resources.getResourceAsReader(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能履行映照文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
//映照sql的标识字符串
String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser";
//履行查询返回1个唯1user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
3、数据表的CRUD操作
3.1 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>
3.2 注解的实现
public interface UserMapper {
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int insertUser(User user);
@Delete("delete from users where id=#{id}")
public int deleteUserById(int id);
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int updateUser(User user);
@Select("select * from users where id=#{id}")
public User getUserById(int id);
@Select("select * from users")
public List<User> getAllUser();
}
在conf.xml中注册这个映照接口:
<mapper class="com.atguigu.ibatis.crud.ano.UserMapper"/>
在DAO类中调用:
public User getUserById(int id) {
SqlSession session = sessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserById(id);
return user;
}
4、几个可以优化的地方
4.1 建立数据库配置文件
## db.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}" />
然后在Mybatis的配置文件conf.xml中加入读取db.properties的配置:
<!-- 引入资源文件 -->
<properties resource="db.properties"/>
4.2 为实体类定义别名
<!-- 配置实体类的别名 -->
<typeAliases>
<!-- <typeAlias type="com.mybatis.test1.User" alias="_User"/> -->
<package name="com.mybatis.bean"/> <!-- 扫描这个包 -->
</typeAliases>
上面的配置可以简化SQL映照xml文件中的援用,不再需要每次都要写类的全路径。
4.3 添加log4j配置文件,打印日志信息
#log4j.properties
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %⑸p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠