码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis入门

时间:2015-04-08 21:38:36      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:mybatis

一、MyBatis介绍

MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。


Mybatis-3.1.1下载地址:http://download.csdn.net/detail/huhui_bj/8575253


二、快速入门

2.1 准备

首先需要添加两个jar包,一个是mybatis-3.1.1.jar,一个是mysql-connector-java-5.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-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-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-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-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";
		//执行查询返回一个唯一user对象的sql
		User user = session.selectOne(statement, 1);
		System.out.println(user);

三、数据表的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.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] %-5p [%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



Mybatis入门

标签:mybatis

原文地址:http://blog.csdn.net/huhui_cs/article/details/44945481

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!