编写排版不易,既然来了,举手之劳,点个赞再走吧
MyBatis框架也被称之为ORM(Object/Relation Mapping,即对象关系映射)框架。所谓的ORM就是一种为了解决面向对象与关系型数据库中数据类型不匹配的技术,它通过描述Java对象与数据库表之间的映射关系,自动将Java应用程序中的对象持久化到关系型数据库的表中。
Mybatis包下载地址:https://github.com/mybatis/mybatis-3/releases
其他包相关链接参考:相关文章
第一步:创建Web项目,在项目的lib目录下导入相关包如图
第二步:MySQL数据库中,创建一个名为mybatis的数据库,在此数据库中创建一个t_customer表,同时预先插入几条数据。
相关Mysql创建语句代码:
#创建mybatis数据库
create database mybatis;
#切换数据库
use mybatis;
#创建t_customer表
create table t_customer (
id int(32) primary key auto_increment,
username varchar(50),
jobs varchar(50),
phone varchar(16)
);
#向t_customer表插入三条数据
insert into t_customer values('1','joy','doctor', '132456952658');
insert into t_customer values('2','tom','teacher', '133452352658');
insert into t_customer values('3','jack','worker', '152356852124');
第三步:在项目的src目录下创建log4j.properties文件。
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.mybatis=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
第四步:在src目录下,创建一个com.mybatis.po包,在该包下创建持久化类Customer,并在类中声明id、username、jobs和phone属性,及其对应的getter/setter方法。
package com.mybatis.po;
/*
* 客户持久化类
*/
public class Customer {
private Integer id ; //主键id
private String username ; //客户名称
private String jobs; //职业
private String phone; //电话
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getJobs() {
return jobs;
}
public void setJobs(String jobs) {
this.jobs = jobs;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "Customer [id="+ id +" , username="+ username +",jobs="+ jobs +",phone="+ phone +"] ";
}
}
第五步:在src目录下,创建MyBatis的核心配置文件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>
<!-- 1.配置环境,默认的环境id为mysql -->
<environments default="mysql">
<!-- 1.2. 配置id为mysql的数据库环境 -->
<environment id="mysql">
<!-- 使用JDBC的事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<!-- 数据库的用户名和密码 -->
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 2.配置Mapper的位置 -->
<mappers>
<mapper resource="com/mybatis/po/CustomerMapper.xml" />
</mappers>
</configuration>
第六步:在src目录下,创建一个com.mybatis.po包,并在包中创建映射文件CustomerMapper.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">
<!-- namespace="表示命名空间 -->
<mapper namespace="com.mybatis.po.CustomerMapper">
<!-- 根据客户编号获取客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="com.mybatis.po.Customer">
select * from t_customer where id = #{id}
</select>
</mapper>
第七步:在src目录下,创建一个com.mybatis.test包,在该包下创建测试类MybatisTest,并在类中编写测试方法findCustomerByIdTest()。
package com.mybatis.test;
import java.io.InputStream;
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 org.junit.Test;
import com.mybatis.po.Customer;
/*
* 入门程序测试类
*/
public class MybatisTest {
/**
* 根据客户编号查询客户信息
*/
@Test
public void findCustomerByIdTest() throws Exception {
//1.获取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//2.根据配置文件构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.通过SqlSession执行映射文件中定义的SQL,并返回映射结果
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.SqlSession 执行映射文件中定义的SQL ,并返回映射结果
Customer customer = sqlSession.selectOne("com.mybatis.po"+".CustomerMapper.findCustomerById",1);
//打印输出结果
System.out.println(customer.toString());
//关闭SqlSession
sqlSession.close();
}
}
到这里就结束了。
在这里如果出现。
包调用错误运行MyBatis出现Exception iin thread “main” java.io.IOException:Could not find resource mybatis-config.xml
解决方法:查看项目下的.classpath文件,发现加载的配置文件位于src目录下,将mybatis-config.xml移动到src目录下。
补充。。。。。。。。。。。。。。。。。。。。
2.根据客户名模糊查询客户信息
在映射文件CustomerMapper.xml中,添加根据客户名模糊查询客户信息列表的SQL语句。
<select id="findCustomerByName" parameterType="String"
resultType="com.myabtis.po.Customer">
select * from t_customer where username like '%${value}%'
</select>
3. 添加客户
添加操作是通过元素来实现的。例如,向数据库中的t_customer表中插入一条数据可以通过如下配置来实现。
<insert id="addCustomer" parameterType="com.mybatis.po.Customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
在测试类MybatisTest中,添加测试方法addCustomerTest()。
public void addCustomerTest() throws Exception{
…
Customer customer = new Customer();
customer.setUsername("rose");
customer.setJobs("student");
customer.setPhone("13333533092");
int rows = sqlSession.insert("com.mybatis.po"
+ ".CustomerMapper.addCustomer", customer);
…
}
4. 更新客户
更新操作在映射文件中是通过配置<update>元素来实现的。
<update id="updateCustomer" parameterType="com.mybatis.po.Customer">
update t_customer set
username=#{username},jobs=#{jobs},phone=#{phone}
where id=#{id}
</update>
在测试类MybatisTest中,添加测试方法updateCustomerTest(),
将id为4的用户职业修改为programmer,电话修改为13311111111。
public void updateCustomerTest() throws Exception{
…
Customer customer = new Customer();
customer.setId(4);
customer.setUsername("rose");
customer.setJobs("programmer");
customer.setPhone("13311111111");
int rows = sqlSession.update("com.mybatis.po"
+ ".CustomerMapper.updateCustomer", customer);
…
}
5. 删除客户
删除操作在映射文件中是通过配置<delete>元素来实现的。
<delete id="deleteCustomer" parameterType="Integer">
delete from t_customer where id=#{id}
</delete>
在测试类MybatisTest中,添加测试方法deleteCustomerTest(),该方法用于将id为4的客户信息删除。
public void deleteCustomerTest() throws Exception{
…
int rows = sqlSession.delete("com.mybatis.po"
+ ".CustomerMapper.deleteCustomer", 4);
…
}