到看这里,现在在返回第一章,hibernate 和 mybatis的区别,是否感觉更加深刻了。
下面我们进入我们本章的重点:
mybatis 实际应用中按照下面的4个步骤:
- 创建实体对象 (User.java)
- 创建操作数据库接口 (UserDao.java)
- 用mapper 完成接口实现 (UserDao.xml) 重点(通过mapper 映射就可以直接调用接口)
- 配置映射文件包(在mybatis-config.xml中配置)
下面是代码:
User.java 代码
package com.zll.mybatis.bean;
import java.util.Date;
public class User {
private int id;
private int parentId;
private int sonId;
private String name;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public int getSonId() {
return sonId;
}
public void setSonId(int sonId) {
this.sonId = sonId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", parentId=" + parentId + ", sonId=" + sonId + ", name=" + name + ", birthday=" + birthday + "]";
}
}
UserDao 代码
package com.zll.mybatis.dao;
import java.util.List;
import com.zll.mybatis.bean.User;
public interface UserDao {
public void insertReteunId(User user) throws Exception;
public void deleteById(int id) throws Exception;
public void updateById(User user) throws Exception;
public List<User> findByName(String username) throws Exception;
}
UserDao.xml 代码 (核心,实现了UserDao的接口)
这里必须做到4个一致:
1、namespace 和 映射对象 包名类名一致。
2、id名称 和 映射对象 方法名 一致
3、parameterType 和 映射对象 参数类型 一致
4、resultType 和 映射对象 返回类型 一致
<?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.zll.mybatis.dao.UserDao">
<!-- 增加用户并返回 id-->
<insert id="insertReteunId" parameterType="com.zll.mybatis.bean.User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
<!-- sql语句,获取最近插入数据的id -->
select last_insert_id();
</selectKey>
insert into user(parentId,sonId,name,birthday) value(#{parentId},#{sonId},#{name},#{birthday})
</insert>
<!-- 删除 -->
<delete id="deleteById" parameterType="int">
delete from user where id=#{id}
</delete>
<!-- 更新 -->
<update id="updateById" parameterType="com.zll.mybatis.bean.User">
update user set parentId=#{parentId},sonId=#{sonId},name=#{name},birthday=#{birthday} where id=#{id}
</update>
<!-- 模糊查询 ${}符号表示sql使用拼接方式,这样会参数sql注入露点,所以大家要注意 -->
<select id="findByName" parameterType="string" resultType="com.zll.mybatis.bean.User">
<!-- select * from user where name like "%${value}%" -->
select * from user where name like #{value}
</select>
</mapper>
最后在在mybatis-config.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/my_db?characterEncoding=UTF8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射路径 添加整个包,就不用每个类都配置了 -->
<package name="com/zll/mybatis/dao"/>
</mappers>
</configuration>
测试代码(直接调用接口完成数据查询):
package com.zll.mybatis.mybatis;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import junit.framework.TestCase;
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.zll.mybatis.bean.User;
import com.zll.mybatis.dao.UserDao;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
SqlSessionFactory sqlSessionFactory;
@Override
protected void setUp() throws Exception {
super.setUp();
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public void insertUser() throws Exception {
SqlSession session = sqlSessionFactory.openSession();
UserDao mapper = session.getMapper(UserDao.class);
User user = new User();
user.setName("小红萝卜");
user.setBirthday(new Date());
mapper.insertReteunId(user);
System.out.println("user id = "+user.getId());
session.close();
}
public void updateUser() throws Exception {
SqlSession session = sqlSessionFactory.openSession();
UserDao mapper = session.getMapper(UserDao.class);
User user = new User();
user.setId(4);
user.setParentId(3);
user.setName("小狗蛋");
user.setBirthday(new Date());
mapper.updateById(user);
session.commit();
session.close();
}
public void findUser() throws Exception {
SqlSession session = sqlSessionFactory.openSession();
UserDao mapper = session.getMapper(UserDao.class);
List<User> list = mapper.findByName("%小%");
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i));
}
session.close();
}
public void deleteUser() throws Exception {
SqlSession session = sqlSessionFactory.openSession();
UserDao mapper = session.getMapper(UserDao.class);
mapper.deleteById(8);
session.commit();
session.close();
}
}