MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。
MyBatis是一个优秀的持久层框架,使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
注:MyBatis和Ibatis是同一个框架。
MyBatis把sql语句交给xml进行管理。
①导入mybatis相关jar包
②写一个sqlMapConfig.xml
提供mybatis的核心配置文件sqlMapConfig.xml,并放在项目的src目录下。此文件中配置了数据库的基本连接参数和sql映射文件等相关信息。我们可以从mybatis安装包中提供的官方文档(mybatis-3.1.1.pdf)中获得此文件的模板。
sqlMapConfig.xml
③创建数据库Mybatis和数据表user
创建与数据表user对应的java实体类User.java
User.java
public class User {
private String id ;
private String name ;
private Integer age ;
private String address ;
public String getId() {
return id ;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age ;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [address=" + address + ",name=" + name + ",age=" + age + ",address" + address + "]" ;
}
}
④创建映射文件
提供User实体的sql映射文件User.xml,并和User实体放在同一个包中,此文件的模板同样可以从mybatis的官方文档(mybatis-3.1.1.pdf)中获得。
user.xml
⑤执行代码
MybatisTest.java
public class MybatisTest {
//根据id查询user
@Test
public void test1() throws IOException{
String resource = "sqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
//参数1:命名空间+sqlId类唯一锁定要执行的sql
//参数2:sql语句所需要的参数
User user = (User)session.selectOne( "cn.itcast.mybatis.domain.User.selectUserById" ,"1" );
System. out.println(user);
session.close();
}
}
⑥执行结果:
(注:mybatis在生成实体对象的时候实际上调用了set方法。)
3、显示执行的sql语句
为了更加直观的看到mybatis执行的sql语句,可以在项目的src目录下加入log4j.properties文件,将程序执行的sql输出到控制台。
02 模拟框架将查询到的数据通过反射包装成指定对象
1、代码
public class MybatisTest {
@Test
public void test2() throws Exception {
String className = "cn.itcast.mybatis.domain.User" ;
Object object = Class. forName(className).newInstance();
Class. forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mybatis", "root","sorry" );
String sql = "select * from user where id = ?" ;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "1");
ResultSet rs = ps.executeQuery();
while(rs.next()){
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
for(int i = 1; i <= count; i++){
String columnName = data.getColumnName(i);
String setMethodName = buildSetMethod(columnName);
String typeName = data.getColumnTypeName(i);
if(typeName.equals("VARCHAR" )){
String value = rs.getString(columnName);
Method method = object.getClass().getMethod(setMethodName, String.class);
method.invoke(object, value);
} else if (typeName.equals("INT")){
int value = rs.getInt(columnName);
Method method = object.getClass().getMethod(setMethodName, Integer.class);
method.invoke(object, value);
}
}
User user = (User)object;
System. out.println(user);
}
}
public String buildSetMethod(String cName){
String c1 = "set";
String c2 = cName.substring(0,1).toUpperCase();
String c3 = cName.substring(1);
return c1 + c2 + c3;
}
}
2、执行结果
03 Mybatis基础代码
sqlMapConfig.xml
User.xml
id,name,age,address
delete from user where id = #{id}
insert into user(id,name,age,address) values(#{id},#{name},#{age},#{address})
update user set name=#{name},age=#{age},address=#{address} where id=#{id}
update user
name = #{name}
age = #{age}
address = #{address}
where id=#{id}
MybatisTest.java
package cn.itcast.mybatis.test;
import cn.itcast.mybatis.domain.User;
public class MybatisTest {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void init() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//根据id查询user
@Test
public void test1() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
//参数1:命名空间+sqlId类唯一锁定要执行的sql
//参数2:sql语句所需要的参数
User user = (User)session.selectOne("cn.itcast.mybatis.domain.User.selectUserById" ,"1" );
System. out.println(user);
session.close();
}
//根据所有的user
@Test
public void test3() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
List users = session.selectList("cn.itcast.mybatis.domain.User.selectAllUser" );
for(User user : users){
System. out.println(user);
}
session.close();
}
//根据用户id删除某个用户
@Test
public void test4() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
int count = session.delete("cn.itcast.mybatis.domain.User.deleteUserById" ,"3" );
System. out.println(count);
//这里一定要注意提交事务,在执行delete操作的时候已经将setAutoCommit设置为false了
session.commit();
session.close();
}
//插入一条用户信息
@Test
public void test5() throws IOException{
User user = new User();
user.setId( "3");
user.setName( "wangwu");
user.setAge(22);
user.setAddress( "tj");
SqlSession session = sqlSessionFactory.openSession();
session.delete( "cn.itcast.mybatis.domain.User.insertUser" ,user);
session.commit();
session.close();
}
//根据id修改用户信息
@Test
public void test6() throws IOException{
User user = new User();
user.setId( "3");
user.setName( "wangwu2");
//如果下面这两条代码不写,那么数据库中的用户的age和address属性将会被设置为null,在mybatis中采用动态sql的方式实现动态拼凑sql语句
//user.setAge(24);
//user.setAddress("tj2");
SqlSession session = sqlSessionFactory.openSession();
session.delete( "cn.itcast.mybatis.domain.User.updateUserById" ,user);
session.commit();
session.close();
}
//动态sql语句更新用户的信息
//这时候一定要注意sql语句可能出现任何信息都不更新的情况,这个时候就应该在页面就拦截住这种查询
@Test
public void test7() throws IOException{
User user = new User();
user.setId( "3");
user.setName( "wangwu3");
SqlSession session = sqlSessionFactory.openSession();
session.delete( "cn.itcast.mybatis.domain.User.updateUserByCondition" ,user);
session.commit();
session.close();
}
//动态sql语句查询所有的用户
@Test
public void test8() throws IOException{
User user = new User();
// user.setId(“1”);
//不传任何条件,就相当于查询出所有的用户数据
SqlSession session = sqlSessionFactory.openSession();
List users = session.selectList("cn.itcast.mybatis.domain.User.selectUserByCondition2" ,user);
for(User user2 : users){
System. out.println(user2);
}
session.commit();
session.close();
}
//利用hashmap传递参数查询用户信息
@Test
public void test9() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
Map map = (Map)session.selectOne("cn.itcast.mybatis.domain.User.selectUserById4Map" ,"1" );
System. out.println(map);
session.close();
}
//利用hashmap传递参数插入用户信息
@Test
public void test10() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
Map map = new HashMap();
map.put( "id", "4" );
map.put( "name", "zl" );
map.put( "age", 28);
map.put( "address", "bz" );
session.insert( "cn.itcast.mybatis.domain.User.insertUser4Map" ,map);
session.commit();
session.close();
}
//模糊查询
@Test
public void test11() throws IOException{
SqlSession session = sqlSessionFactory.openSession();
User user = new User();
user.setName( "wang");
User user2 = session.selectOne("cn.itcast.mybatis.domain.User.selectUserByCondition3" ,user);
System. out.println(user2);
session.close();
}
}
04 Mybatis中的关联映射
1、建表、插入数据
2、代码
Customer.java
insert into customer(id,name,age,address) values
(#{obj.id},#{obj.name},#{obj.age},#{obj.address})
Order.java
sqlMapConfig.xml
Customer.xml
public class Customer {
private String id ;
private String name ;
private Integer age ;
private String address ;
Set orders = new HashSet();
public String getId() {
return id ;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age ;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this.address = address;
}
public Set getOrderss() {
return orders ;
}
public void setOrderss(Set orders) {
this.orders = orders;
}
public String toString(){
return "Customer[address=" + address + ",age=" + age + ",id=" + id + ",name=" + name + ",orders=" + orders + "]";
}
}
Order.xml
public class Order {
private String orderId ;
private String orderNumber ;
private Integer orderPrice ;
private Customer cus = new Customer();
public String getOrderId() {
return orderId ;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderNumber() {
return orderNumber ;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public Integer getOrderPrice() {
return orderPrice ;
}
public void setOrderPrice(Integer orderPrice) {
this.orderPrice = orderPrice;
}
public Customer getCus() {
return cus ;
}
public void setCus(Customer cus) {
this.cus = cus;
}
}
MybatisTest2.java
public class MybatisTest2 {
private SqlSessionFactory sqlSessionFactory = null;
@Before
public void init() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test1() throws IOException{
SqlSession session = sqlSessionFactory .openSession();
Customer cus = (Customer)session.selectOne("cn.itcast.mybatis.domain.Customer.selectCustomerById" ,"1" );
System. out.println(cus);
session.close();
}
@Test
public void test2() throws IOException{
SqlSession session = sqlSessionFactory .openSession();
Order order = session.selectOne("cn.itcast.mybatis.domain.Order.selectOrderById" ,"001" );
System. out.println(order);
session.close();
}
@Test
public void test3() throws IOException{
SqlSession session = sqlSessionFactory .openSession();
List customers = new ArrayList();
for(int i = 0; i < 10; i++){
Customer customer = new Customer();
customer.setId(UUID. randomUUID().toString());
customer.setName( "customer" + i);
customer.setAge(i);
customer.setAddress( "address" + i);
customers.add(customer);
}
session.insert( "cn.itcast.mybatis.domain.Customer.insertBatch" ,customers);
session.commit();
session.close();
}
}
05 Spring与Mybatis的整合
1、导入jar包
2、代码
User.java
public class User {
private String id ;
private String name ;
private Integer age ;
private String address ;
public String getId() {
return id ;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age ;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [address=" + address + ",name=" + name + ",age=" + age + ",address" + address + "]" ;
}
}
User.xml
id,name,age,address
delete from user where id = #{id}
insert into user(id,name,age,address) values(#{id},#{name},#{age},#{address})
update user set name=#{name},age=#{age},address=#{address} where id=#{id}
update user
name = #{name}
age = #{age}
address = #{address}
where id=#{id}
IUserDao.xml
public interface IUserDao {
public User findUserById(String id);
public int insertUser(User user);
}
UserDaoImpl.java
public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao {
// private SqlSessionFactory sf;
//
// public SqlSessionFactory getSf() {
// return sf;
// }
//
// public void setSf(SqlSessionFactory sf) {
// this.sf = sf;
// }
public User findUserById(String id) {
// SqlSession session = sf.openSession();
SqlSession session = this.getSqlSession();
User user = (User)session.selectOne("cn.itcast.mybatis.domain.User.selectUserById" ,id);
// session.close();
return user;
}
public int insertUser(User user) {
// SqlSession session = sf.openSession();
SqlSession session = this.getSqlSession();
int i = session.insert("cn.itcast.mybatis.domain.User.insertUser" ,user);
// int c = 1/0;
// session.close();
return i;
}
}
IUserService.java
public interface IUserService {
public User findUserById(String id);
public int insertUser(User user);
}
UserServiceImpl.java
public class UserServiceImpl implements IUserService {
private IUserDao userDao ;
public IUserDao getUserDao() {
return userDao ;
}
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public User findUserById(String id) {
return userDao .findUserById(id);
}
public int insertUser(User user) {
return userDao .insertUser(user);
}
}
sqlMapConfig.xml
beans.xml
MybatisSpringTest.java public class MybatisSpringTest { } 06 SSI Struts+Spring+Ibatis整合 User.java public class User { } User.xml IUserDao.java public interface IUserDao { } UserDaoImpl.java public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao { } IUserService.java public interface IUserService { } UserServiceImpl.java public class UserServiceImpl implements IUserService { } UserAction.java public class UserAction extends ActionSupport { } struts.xml sqlMapConfig.xml beans.xml web.xml updateUser.jsp <%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"?/" +request.getServerName()+":"+request.getServerPort()+path+ “/”; %> user.jsp <%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"?/" +request.getServerName()+":"+request.getServerPort()+path+ “/”; %> userList.jsp <%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %> <%@ taglib prefix =“s” uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"?/" +request.getServerName()+":"+request.getServerPort()+path+ “/”; %> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
@Test
public void test1(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml" );
IUserService s = (IUserService)ctx.getBean( "userService");
User user = s.findUserById( "1");
System. out.println(user);
}
@Test
public void test2(){
//利用下面这种方式,自动进行了事务提交,即使出现异常,也会插入成功,所以需要使用事务管理器进行管理
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml" );
IUserService s = (IUserService)ctx.getBean( "userService");
User user = new User();
user.setId( "121");
user.setName( "ddd");
user.setAge(30);
user.setAddress( "beijing");
int i = s.insertUser(user);
System. out.println(i);
}
private String id ;
private String name ;
public String getName() {
return name ;
}
public void setName(String userName) {
this.name = userName;
}
private Integer age ;
private String address ;
public String getId() {
return id ;
}
public void setId(String id) {
this.id = id;
}
public Integer getAge() {
return age ;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [address=" + address + ", age=" + age + ", id=" + id
+ ", name=" + name + "]";
}
public User findUserById(String id);
public int insertUser(User u);
public List
public User findUserById(String id) {
SqlSession session = this.getSqlSession();
User user = (User)session.selectOne("cn.itcast.mybatis.domain.User.selectUserById" , id);
//session.close();
return user;
}
public int insertUser(User u) {
SqlSession session = this.getSqlSession();
int i = session.insert("cn.itcast.mybatis.domain.User.insertUser" , u);
//session.close();
return i;
}
public int deleteUserById(String id) {
int i = this.getSqlSession().delete("cn.itcast.mybatis.domain.User.deleteUserById" , id);
return i;
}
public List
public User findUserById(String id);
public int insertUser(User u);
public List
private IUserDao userDao ;
public IUserDao getUserDao() {
return userDao ;
}
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public User findUserById(String id) {
return userDao .findUserById(id);
}
public int insertUser(User u) {
int i = userDao .insertUser(u);
//int c = 1/0;
return i;
}
public int deleteUserById(String id) {
// TODO Auto-generated method stub
return userDao .deleteUserById(id);
}
public List
private IUserService userService ;
private String id ;
private User user ;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public User getUser() {
return user ;
}
public void setUser(User user) {
this.user = user;
}
public String getId() {
return id ;
}
public void setId(String id) {
this.id = id;
}
public String findUserByid(){
User user = userService.findUserById(id );
System. out.println(user);
return "user" ;
}
public String insertUser(){
int i = userService .insertUser(user);
System. out.println(i);
return "user" ;
}
public String deleteUser(){
int i = userService .deleteUserById(id);
System. out.println(i);
return "showUsers" ;
}
public String findAllUser(){
List
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
This is user.jsp
id td>
name
age
address
delete
update
< s:property value="id"/> td>
< s:property value="name"/> td>
< s:property value="age"/> td>
< s:property value="address"/> td>
"> delete
"> update