上一篇我们讲了MyBatis配置文件中的配置及其优化:https://blog.csdn.net/qq_38720976/article/details/84484034
本文将通过项目使用MyBatis对表执行CRUD操作
mybatis-3.3.0.jar下载路径:https://github.com/mybatis/mybatis-3/releases
1.主配置文件mybatis.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" />
<!-- 数据库连接URL-->
<property name="url" value="jdbc:mysql://localhost:3306/mysqljdbc?characterEncoding=utf-8" />
<!-- 数据库用户名和密码 -->
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<!-- 在配置文件中 关联包下的实体类的映射文件-->
<mappers>
<mapper resource="com/aiit/dao/UserMapper.xml"/>
</mappers>
</configuration>
2.实体映射文件配置UserMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
-->
<mapper namespace="com.aiit.dao.UserMapper">
<!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
resultType="com.aiit.pojo.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类
-->
<select id="selectOne" parameterType="int" resultType="com.aiit.pojo.User">
SELECT * FROM tbl_user WHERE tbl_user.id=#{id}
</select>
<select id="selectAll" resultType="com.aiit.pojo.User">
SELECT * FROM tbl_user
</select>
<insert id="insertOne" parameterType="com.aiit.pojo.User" >
INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth)
VALUES(#{name},#{age},#{address},#{birth})
</insert>
<update id="updateOne" parameterType="com.aiit.pojo.User">
update tbl_user set tbl_user.address = #{address} where id = #{id}
</update>
<delete id="deleteOne" parameterType="com.aiit.pojo.User">
delete from tbl_user where id = #{id}
</delete>
</mapper>
3.User.java
package com.aiit.pojo;
import java.util.Date;
public class User {
private int id;
private String name;
private int age;
private String address;
private Date birth;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public User() {
super();
}
public User(int id, String name, int age, String address, Date birth) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.birth = birth;
}
public User(String name, int age, String address, Date birth) {
super();
this.name = name;
this.age = age;
this.address = address;
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", birth=" + birth + "]";
}
public User(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public User(int id, String address) {
super();
this.id = id;
this.address = address;
}
}
4.TestMyBatisDemo 测试类
package com.aiit.test;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.aiit.pojo.User;
public class TestMyBatisDemo {
/**
* @param args
*/
public static void main(String[] args) {
String resource="mybatis.cfg.xml";
InputStream inputStream = TestMyBatisDemo.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = factory.openSession();
//1.查询
String statement1 = "com.aiit.dao.UserMapper.selectOne";
User user1 = session.selectOne(statement1,1);
System.out.println("查询结果: " + user1);
// 2.添加
// String string = "2016-10-24";
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// try {
// User user2 = new User("beifang", 15, "Chain",sdf.parse(string));
// String statement2 = "com.aiit.dao.UserMapper.insertOne";
// int insertResult= session.insert(statement2,user2);
// System.out.println("插入成功"+insertResult);
// } catch (ParseException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// 3.修改
// String statement3 = "com.aiit.dao.UserMapper.updateOne";
// User user3 = new User(6, "中国");
// int updateResult = session.update(statement3, user3);
// System.out.println("修改成功"+updateResult);
//4.删除
//String statement4 = "com.aiit.dao.UserMapper.deleteOne";
//int deleteResult= session.delete(statement4, 2);
//System.out.println("删除成功"+deleteResult);
//5.查询所有
String statement5 = "com.aiit.dao.UserMapper.selectAll";
List<User> users = session.selectList(statement5);
for(User user : users ) {
System.out.println(user.getId()+" , "+user.getName()+" , "+user.getAge()+" , "+user.getAddress()+" , "+user.getBirth());
}
session.commit();
session.close();
}
}
测试效果控制台输出:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/D:/Users/Administrator/eclipse-workspace/Mybatis_frist/WebRoot/WEB-INF/lib/mybatis-3.2.7.jar) to method java.lang.Class.checkPackageAccess(java.lang.SecurityManager,java.lang.ClassLoader,boolean)
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
查询结果: User [id=1, name=jim, age=19, address=USA, birth=Fri Dec 11 00:00:00 CST 1998]
插入成功1
修改成功1
删除成功1
1 , jim , 19 , USA , Fri Dec 11 00:00:00 CST 1998
3 , 李雷 , 9 , China , Fri Dec 11 00:00:00 CST 2009
6 , beifang , 15 , 中国 , Mon Oct 24 00:00:00 CST 2016