Mybatis学习三 (CRUD)
1.示例
第一步:配置数据源和对象(表)的映射
加入所需的 jar
包:mysql-connector
和 mybatis3.jar
。配置 src/config/Configure.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>
<typeAliases>
<typeAlias alias="User" type="com.yiibai.mybatis.models.User" />
</typeAliases>
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="User" type="com.yiibai.mybatis.models.User" />
</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/testdb" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<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/testdb" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- // power by http://www.yiibai.com -->
<mapper resource="com/yiibai/mybatis/models/User.xml" />
</mappers>
</configuration>
<!-- // power by http://www.yiibai.com -->
<mapper resource="com/yiibai/mybatis/models/User.xml" />
</mappers>
</configuration>
第二步:配置表对象(实体类)
public class User {
private int id;
private String name;
private String dept;
private String phone;
private String website;
}
private int id;
private String name;
private String dept;
private String phone;
private String website;
}
第三步:配置接口
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.models.User;
public interface IUser {
//@Select("select * from user where id= #{id}")
//public User getUserByID(int id);
public List<User> getUserList();
//@Select("select * from user where id= #{id}")
//public User getUserByID(int id);
public List<User> getUserList();
public void insertUser(User user);
public void updateUser(User user);
public void deleteUser(int userId);
public User getUser(int id);
}
第四步:配置映射文件(User.xml)}
<?xml version="1.0" encoding="UTF-8"?>
<insert id="insertUser" parameterType="User">
INSERT INTO USER(name,
dept, website,phone)
VALUES(#{name}, #{dept}, #{website}, #{phone})
</insert>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yiibai.mybatis.dao.IUser">
<select id="getUser" parameterType="int"
resultType="com.yiibai.mybatis.models.User">
SELECT *
FROM USER
WHERE id = #{userId}
</select>
resultType="com.yiibai.mybatis.models.User">
SELECT *
FROM USER
WHERE id = #{userId}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO USER(name,
dept, website,phone)
VALUES(#{name}, #{dept}, #{website}, #{phone})
</insert>
<select id="getUserList" resultType="com.yiibai.mybatis.models.User">
SELECT * FROM USER
</select>
SELECT * FROM USER
</select>
<update id="updateUser" parameterType="User">
UPDATE USER
SET
name=
#{name},
dept = #{dept},
website = #{website},
phone = #{phone}
WHERE
id =
#{id}
</update>
UPDATE USER
SET
name=
#{name},
dept = #{dept},
website = #{website},
phone = #{phone}
WHERE
id =
#{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM USER WHERE id = #{id}
</delete>
DELETE FROM USER WHERE id = #{id}
</delete>
</mapper>
第五步:测试
import java.io.Reader;
import java.text.MessageFormat;
import java.util.List;
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.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;
import java.util.List;
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.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;
public class Main {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("config/Configure.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
reader = Resources.getResourceAsReader("config/Configure.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
return sqlSessionFactory;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession session = sqlSessionFactory.openSession();
try {
//sqlSessionFactory.getConfiguration().addMapper(IUser.class);
//User user = (User) session.selectOne( "com.yiibai.mybatis.models.UserMapper.getUserByID", 1);
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession session = sqlSessionFactory.openSession();
try {
//sqlSessionFactory.getConfiguration().addMapper(IUser.class);
//User user = (User) session.selectOne( "com.yiibai.mybatis.models.UserMapper.getUserByID", 1);
// 用户数据列表
getUserList();
// 插入数据
// testInsert();
getUserList();
// 插入数据
// testInsert();
// 更新用户
//testUpdate();
//testUpdate();
// 删除数据
//testDelete();
//testDelete();
} finally {
session.close();
}
}
session.close();
}
}
//
public static void testInsert()
{
try
{
// 获取Session连接
SqlSession session = sqlSessionFactory.openSession();
// 获取Mapper
IUser userMapper = session.getMapper(IUser.class);
System.out.println("Test insert start...");
// 执行插入
User user = new User();
user.setId(0);
user.setName("Google");
user.setDept("Tech");
user.setWebsite("http://www.google.com");
user.setPhone("120");
userMapper.insertUser(user);
// 提交事务
session.commit();
public static void testInsert()
{
try
{
// 获取Session连接
SqlSession session = sqlSessionFactory.openSession();
// 获取Mapper
IUser userMapper = session.getMapper(IUser.class);
System.out.println("Test insert start...");
// 执行插入
User user = new User();
user.setId(0);
user.setName("Google");
user.setDept("Tech");
user.setWebsite("http://www.google.com");
user.setPhone("120");
userMapper.insertUser(user);
// 提交事务
session.commit();
// 显示插入之后User信息
System.out.println("After insert");
getUserList();
System.out.println("Test insert finished...");
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("After insert");
getUserList();
System.out.println("Test insert finished...");
}
catch (Exception e)
{
e.printStackTrace();
}
}
// 获取用户列表
public static void getUserList() {
try {
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
// 显示User信息
System.out.println("Test Get start...");
printUsers(iuser.getUserList());
System.out.println("Test Get finished...");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getUserList() {
try {
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
// 显示User信息
System.out.println("Test Get start...");
printUsers(iuser.getUserList());
System.out.println("Test Get finished...");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testUpdate()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test update start...");
printUsers(iuser.getUserList());
// 执行更新
User user = iuser.getUser(1);
user.setName("New name");
iuser.updateUser(user);
// 提交事务
session.commit();
// 显示更新之后User信息
System.out.println("After update");
printUsers(iuser.getUserList());
System.out.println("Test update finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test update start...");
printUsers(iuser.getUserList());
// 执行更新
User user = iuser.getUser(1);
user.setName("New name");
iuser.updateUser(user);
// 提交事务
session.commit();
// 显示更新之后User信息
System.out.println("After update");
printUsers(iuser.getUserList());
System.out.println("Test update finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
// 删除用户信息
public static void testDelete()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test delete start...");
// 显示删除之前User信息
System.out.println("Before delete");
printUsers(iuser.getUserList());
// 执行删除
iuser.deleteUser(2);
// 提交事务
session.commit();
// 显示删除之后User信息
System.out.println("After delete");
printUsers(iuser.getUserList());
System.out.println("Test delete finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
public static void testDelete()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test delete start...");
// 显示删除之前User信息
System.out.println("Before delete");
printUsers(iuser.getUserList());
// 执行删除
iuser.deleteUser(2);
// 提交事务
session.commit();
// 显示删除之后User信息
System.out.println("After delete");
printUsers(iuser.getUserList());
System.out.println("Test delete finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
* 打印用户信息到控制台
*
* @param users
*/
private static void printUsers(final List<User> users) {
int count = 0;
*
* 打印用户信息到控制台
*
* @param users
*/
private static void printUsers(final List<User> users) {
int count = 0;
for (User user : users) {
System.out.println(MessageFormat.format(
"============= User[{0}]=================", ++count));
System.out.println("User Id: " + user.getId());
System.out.println("User Name: " + user.getName());
System.out.println("User Dept: " + user.getDept());
System.out.println("User Website: " + user.getWebsite());
}
}
}
System.out.println(MessageFormat.format(
"============= User[{0}]=================", ++count));
System.out.println("User Id: " + user.getId());
System.out.println("User Name: " + user.getName());
System.out.println("User Dept: " + user.getDept());
System.out.println("User Website: " + user.getWebsite());
}
}
}
学习来源:https://www.yiibai.com/mybatis/mybatis-curd.html#article-start