MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
要使用 MyBatis, 只需将 mybatis-x.x.x.jar文件置于 classpath 中即可。
如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>x.x.xversion>
dependency>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
jdbc.username=root
jdbc.password=yourpassword
注意行末不能有多余的空格。
同时将mysql驱动添加到工程中。
package sample.mybatis;
public class User {
private int id;
private String userName;
private int userAge;
private String userAddress;
public User(){}
public User(int id, String userName, int userAge, String userAddress)
{
this.id = id;
this.userName = userName;
this.userAge = userAge;
this.userAddress = 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 int getUserAge()
{
return userAge;
}
public void setUserAge(int userAge)
{
this.userAge = userAge;
}
public String getuserAddress()
{
return userAddress;
}
public void setUserAddress(String userAddress)
{
this.userAddress = userAddress;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + userName + ", userAge=" + userAge + ", address=" + userAddress + "]";
}
}
<mapper namespace="org.mybatis">
<resultMap type="User" id="UserList">
<result property="id" column="id" />
<result property="userName" column="userName"/>
<result property="userAge" column="userAge" />
<result property="userAddress" column="userAddress"/>
resultMap>
<select id="selectAllUserId" resultType="java.lang.Integer">
select id from user
select>
<select id="findUserById" parameterType="int" resultType="User">
SELECT * FROM USER WHERE id=#{id}
select>
<insert id="insertIntoUser" parameterType="User">
insert into USER (id, userName, userAge, userAddress) values (
#{id}, #{userName}, #{userAge}, #{userAddress}
)
insert>
<insert id="insertUsers" useGeneratedKeys="true" keyProperty="id">
insert into user (id, userName, userAge, userAddress) values
<foreach item="item" collection="list" separator=",">
(#{item.id}, #{item.userName}, #{item.userAge}, #{item.userAddress})
foreach>
insert>
<update id="updateUser" parameterType="User">
update user
<set>
<if test="userName != null">userName = #{userName},if>
<if test="userAge != null">userAge = #{userAge},if>
<if test="userAddress != null">userAddress = #{userAddress}if>
set>
where id = #{id}
update>
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{id}
delete>
mapper>
<configuration>
<properties resource="db.properties">
properties>
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
<typeAliases>
<typeAlias type="sample.mybatis.User" alias="User"/>
<package name="com.huawei.test"/>
typeAliases>
<typeHandlers>
typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="sqlmap/User.xml"/>
mappers>
configuration>
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 sample.mybatis.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MybatisFirst {
//保存数据库中已有的主键。
private static List allUserId = new ArrayList();
private static final String resource = "SqlMapConfig.xml";
private SqlSessionFactory sqlSessionFactory;
MybatisFirst() throws IOException
{
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//根据主键选择用户
public void selectUserById(int selectId)
{
SqlSession session = sqlSessionFactory.openSession();
try{
User user = session.selectOne("org.mybatis.findUserById", selectId);
System.out.println("id 为"+selectId+"的User信息为:"+user);
} finally {
session.close();
}
}
//选取所有的主键
public void selectAllUserId()
{
SqlSession session = sqlSessionFactory.openSession();
try{
allUserId = session.selectList("org.mybatis.selectAllUserId");
System.out.println("所有的ID为:");
for(Integer integer : allUserId)
{
System.out.println(integer);
}
} finally {
session.close();
}
}
//插入一个用户
public void insertIntoUser(User user)
{
SqlSession session = sqlSessionFactory.openSession();
try {
session.selectOne("org.mybatis.insertIntoUser", user);
System.out.println("插入的的User信息为:"+user);
} finally {
session.close();
}
}
//插入用户List
public void insertUsers(List userList)
{
SqlSession session = sqlSessionFactory.openSession();
try {
session.selectOne("org.mybatis.insertUsers", userList);
System.out.println("插入的Users信息为:");
for(User user : userList)
{
System.out.println(user);
}
} finally {
session.close();
}
}
//更新用户
public void updateUser(User user)
{
SqlSession session = sqlSessionFactory.openSession();
try {
session.selectOne("org.mybatis.updateUser", user);
System.out.println("更新后的用户信息为:" + user);
} finally {
session.close();
}
}
//通过主键删除用户
public void deleteUserById(int deleteId)
{
SqlSession session = sqlSessionFactory.openSession();
try{
User user = session.selectOne("org.mybatis.deleteUser", deleteId);
System.out.println(user);
} finally {
session.close();
}
}
public void deleteAllUsers()
{
SqlSession session = sqlSessionFactory.openSession();
try{
for(Integer integer : allUserId)
{
User user = session.selectOne("org.mybatis.deleteUser", integer);
System.out.println(user);
}
} finally {
session.close();
}
}
public boolean isAllUserIdContains(Integer Id)
{
for(Integer integer : allUserId)
{
if(integer.equals(Id))
{
return true;
}
}
return false;
}
//随机生成用户
public List createUser(int userNumber)
{
List userList = new ArrayList();
Random random = new Random();
for(int i = 0; i < userNumber; i++)
{
User user = new User();
Integer Id = Integer.valueOf(random.nextInt(1000000));
while(isAllUserIdContains(Id))
{
Id = Integer.valueOf(random.nextInt(1000000));
}
allUserId.add(Id);
user.setId(Id);
user.setUserAge(random.nextInt(100));
user.setUserName(getRandomString(10));
user.setUserAddress(getRandomString(10));
userList.add(user);
}
return userList;
}
public static String getRandomString(int length)
{
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length; i++)
{
sb.append(str.charAt(random.nextInt(62)));
}
return sb.toString();
}
}
import sample.mybatis.User;
import java.io.IOException;
import java.util.List;
public class TestMybatis {
public static void main(String[] args) throws IOException
{
MybatisFirst mybatis = new MybatisFirst();;
mybatis.deleteAllUsers();
mybatis.selectAllUserId();
List userList = mybatis.createUser(20);
User user = new User(3, "l84102261", 21, "Xi'an");
mybatis.updateUser(user);
mybatis.selectUserById(3);
mybatis.insertUsers(userList);
mybatis.deleteAllUsers();
mybatis.insertIntoUser(user);
}
}