1.效果图:
2.Mybatis的步骤:
本内容涉及到mysql数据库,先去下载一个数据库,新建一个User表和Article表
Create TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; Insert INTO `user` VALUES ('1', 'summer', '100', 'shanghai,pudong');
Drop TABLE IF EXISTS `article`; Create TABLE `article` ( `id` int(11) NOT NULL auto_increment, `userid` int(11) NOT NULL, `title` varchar(100) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- 添加几条测试数据 -- ----------------------------
Insert INTO `article` VALUES ('1', '1', '11111', 'dsgfd');
Insert INTO `article` VALUES ('2', '1', '22222', 'dfsdgds');
Insert INTO `article` VALUES ('3', '1', 'dddd3','dfsfsdfd');
Insert INTO `article` VALUES ('4', '1', 'ddd4', '5555');
2.1先将mybatis-3.2.7.jar和mysql-connector-java-5.1.22-bin.jar两个需要用到的jar包拷到WEB-INF下面的lib文件夹
2.2 看上图中的架构,新建包和类,按顺序新建
Article类:
package com.mybatis.model;
public class Article {
private int id;
private User user;
private String title;
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
User类:
package com.mybatis.model;
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;
}
}
IUserOperation接口:
package com.mybatis.interfaces;
import com.mybatis.model.*;
import java.util.List;
public interface IUserOperation {
//定义的接口名需与User.xml里的id值要对应
public List<User> getUserList(String userName);
public List<Article> getUserAticles(int id);
public User selectUserByID(int id);
public int insertUserInfo(User user);
public int updateUserInfo(User user);
public int deleteUserInfo(int id);
}
新建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.mybatis.interfaces.IUserOperation">
<!-- 通过用户id返回用户信息 -->
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
<!-- 返回List而定义的resultMap,注意column是数据库中定义的列字段,而property是我们自定义的字段,能够解决属性和数据库字段不一致的问题 -->
<resultMap type="User" id="resultUserList">
<id column="id" property="id"></id>
<result column="userName" property="userName"/>
<result column="userAge" property="userAge"/>
<result column="userAddress" property="userAddress"/>
</resultMap>
<!-- 通过用户名返回用户列表 -->
<!-- 记住:在获取List列表的时候,resultMap="resultUserList"千万别写成resultType="resultUserList",否则报错 -->
<select id="getUserList" parameterType="string" resultMap="resultUserList">
select * from `user` where userName like #{userName}
</select>
<!-- 记住type="Article"新加一个class,要去configuration.xml进行别名定义,否则找不到报错 -->
<!-- 通过association来关联user,达到多对一的效果,多篇文章对应一个用户 -->
<!-- column="aid"给数据库列id命了一个别名,区分关联的id,否则只能查询出一条数据 -->
<resultMap type="Article" id="resultUserArticleList">
<id column="aid" property="id"></id>
<result column="title" property="title"/>
<result column="content" property="content"/>
<!-- <association property="user" javaType="User">
<id column="id" property="id"></id>
<result column="userName" property="userName"/>
<result column="userAddress" property="userAddress"/>
</association> -->
<!-- 上面的association等同于下面的这个,前提条件是之前就已经定义过resultUserList -->
<association property="user" javaType="User" resultMap="resultUserList"></association>
</resultMap>
<!-- 获取用户的多个文章 -->
<select id="getUserAticles" parameterType="int" resultMap="resultUserArticleList">
select user.id,user.userName,user.userAddress,
article.id aid,article.title,article.content
from user,article
where user.id=article.userid and user.id=#{id}
</select>
<!-- useGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;keyProperty="id"指定把获取到的主键值注入到User的id属性 -->
<insert id="insertUserInfo" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into `user`(userName,userAge,userAddress) values (#{userName},#{userAge},#{userAddress})
</insert>
<update id="updateUserInfo" parameterType="User">
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
</update>
<delete id="deleteUserInfo" parameterType="int">
delete from `user` where id=#{id}
</delete>
</mapper>
<!-- namespace命名空间中的值一定要对应包定义的接口"com.mybatis.interfaces.IUserOperation",否则报错 -->
新建配置文件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>
<!-- mybatis别名定义 -->
<typeAliases>
<typeAlias alias="User" type="com.mybatis.model.User" />
<typeAlias alias="Article" type="com.mybatis.model.Article" />
</typeAliases>
<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="password" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/model/User.xml" />
</mappers>
</configuration>
<!-- Ctrl+Shift+F 自动排版 -->
最后开始测试,新建一个测试类:
package com.mybatis.test;
import com.mybatis.interfaces.IUserOperation;
import com.mybatis.model.User;
import com.mybatis.model.Article;
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 java.util.List;
public class Test {
private static SqlSessionFactory sqlFactory;
private static Reader reader;
private static User user;
private static int Ret;
/*static{}(即static块),会在类被加载的时候执行且仅会被执行一次,一般用来初始化静态变量和调用静态方*/
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlFactory;
}
//获取用户列表
public static void GetUserList(List<User> UserList)
{
if(UserList.size()>0){
for(User u:UserList){
System.out.println("Id:"+u.getId()+";UserName:"+u.getUserName()+";UserAge:"+u.getUserAge()+
";UserAddress:"+u.getUserAddress());
}
}
else{
System.out.println("用户不存在!");
}
}
//获取用户文章列表
public static void GetUserArticle(List<Article> articleList)
{
if(articleList.size()>0){
for(Article a:articleList){
System.out.println("UserName:"+a.getUser().getUserName()+";UserAddress:"+a.getUser().getUserAddress()+
";ArticleTitle:"+a.getTitle()+";ArticleContent:"+a.getContent());
}
}
else{
System.out.println("用户不存在!");
}
}
public static void main(String[] args) {
SqlSession session = sqlFactory.openSession();
try {
IUserOperation operation=session.getMapper(IUserOperation.class);
//新增
/*user=new User();
user.setUserName("Amyli");
user.setUserAge("20");
user.setUserAddress("Ludun BaLin");
Ret=operation.insertUserInfo(user);
if(Ret>0){
System.out.println("新增成功!");
}
else{
System.out.println("新增失败!");
}*/
//删除
/*Ret=operation.deleteUserInfo(27);
if(Ret>0){
System.out.println("删除成功!");
}
else{
System.out.println("删除失败!");
}*/
//修改
user = operation.selectUserByID(24);
user.setUserAge("23");
user.setUserAddress("Chendu SiChuan");
Ret=operation.updateUserInfo(user);
if(Ret>0){
System.out.println("修改成功!");
}
else{
System.out.println("修改失败!");
}
session.commit(); //记住,做增删改操作,一定要记得调用commit提交,否则无效。
//查询
user = operation.selectUserByID(24);
System.out.println(user.getId());
System.out.println(user.getUserName());
System.out.println(user.getUserAge());
System.out.println(user.getUserAddress());
System.out.println("");
Test.GetUserList(operation.getUserList("DaLei"));
System.out.println("文章:");
Test.GetUserArticle(operation.getUserAticles(24));
} finally {
session.close();
}
}
}
里面有好几个细节要注意,具体看代码,里面有详细注释!
Mybatis代码下载 :Mybatis代码