赞
踩
它封装了JDBC操作的繁琐操作,对JDBC进行了封装,它相比传统的JDBC访问数据库,性能更加优异,具有高度的灵活性、可优化性和易于维护等特点,我们只需要关注 sql语句本身, 而不需要花费精力去处理加载驱动、创建连接、创建 statement 等繁杂的过程。
- 下载MyBatis包,下载地址https://github.com/mybatis/mybatis-3/releases
- 我下载的版本是3.5.5,下载后解压,解压之后的目录是这样的
- 找到lib目录,把lib目录里的jar包全部拷贝到java项目中
- 导入数据库驱动包,下载地址https://dev.mysql.com/downloads/connector/j/
- 这时候我们的工程目录下是这样的
- 找到我们刚才下载的Mybatis包,并解压
- 解压之后,进入这个目录mybatis-3.5.5/mybatis-3.5.5/org/apache/ibatis/builder/xml,找到如下两个文件
- 在Eclipse中配置mybatis-3-config.dtd和mybatis-3-mapper.dtd,目的是让后面的xml文件的时候有标签提示
- 在src目录下创建jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/你的数据库名?characterEncoding=UTF-8 jdbc.username=你的数据库登录账号 jdbc.password=你的数据库登录密码- 在src目录下创建sqlMapConfig.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> <!-- 引入jdbc.properties --> <properties resource="jdbc.properties" /> <environments default="develop"> <!-- 配置开发环境和正式环境 --> <environment id="develop"> <!-- 必须先配置事务管理方式 type:JDBC 把事务交给JDBC来管理 type:MANAGED 自己管理事务 --> <transactionManager type="JDBC"></transactionManager> <!-- 其次配置数据库连接池(数据源) POOLED:使用连接池(数据源),推荐 UNPOOLED:不使用 JNDI:已经过时 --> <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> <!-- <environment id=""> </environment> --> </environments> <mappers> <mapper resource="com/tedu/pojo/EmpMapper.xml" /> </mappers> </configuration>- 在src目录下创建log4j.properties,目的是让控制台看到日志
# Global logging configuration log4j.rootLogger=DEBUG, stdout # 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目录下创建如下几个类
- 稍等我们来解释各个类的作用及含义,我在本地创建了一张表,如下:
- People是一个简单的bean类
package com.tedu.pojo; public class People { //声明私有属性 private Integer id; private String name; private String gender; private String birthday; private String job; private String salary; private String bonus; private String home; private String pass; public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getBonus() { return bonus; } public void setBonus(String bonus) { this.bonus = bonus; } public String getHome() { return home; } public void setHome(String home) { this.home = home; } //提供toString方法 @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", job=" + job + ", salary=" + salary + "]"; } }- PeopleMapper.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.tedu.dao.PeopleMapper"> <!-- 优化内容1:提取公共查询列的语句,需要的地方通过<include refid="columns"></include>来替换 --> <sql id="columns">id,name,salary</sql> <!-- 查询所有员工信息,返回list<People>集合, 查询结果返回java对象,再把这些对象封装到一个集合中,resultType指定结果类型。表示将查询结果封装到People对象中 --> <select id="selectAll" resultType="com.tedu.pojo.People"> select <include refid="columns"></include> from people </select> <!-- 新增数据 --> <update id="insert">insert into people values(null,'马化腾','男','1978-02-03','开淘宝的','500','700','河北',123) </update> <!-- 新增数据 --> <update id="insertdata">insert into people values(null,#{name},#{gender},#{birthday},#{job},#{salary},#{bonus},#{home},#{pass}) </update> <!-- 修改数据 --> <update id="update">update people set salary='5000' where name='马云' </update> <!-- 修改数据 --> <update id="updatedata">update people set salary=#{salary} where name=#{name} </update> <!-- 删除数据 --> <update id="delete">delete from people where name='马化腾'</update> <!-- 删除数据 --> <update id="deletedata">delete from people where name=#{name}</update> <!-- 查询单个数据,必须指定类型 --> <select id="selectOne" resultType="com.tedu.pojo."> select <include refid="columns"></include> from people where id=#{id} </select> <!-- 查询特定条件区间的数据 --> <select id="selectOnly" resultType="com.tedu.pojo.People"> select <include refid="columns"></include> from people where salary between #{smallSalary} and #{bigSalary} </select> <!-- 查询特定列的数据 --> <select id="selectSomeColumn" resultType="com.tedu.pojo.People">select ${columns} from people </select> <!-- 模糊查询 --> <select id="selectLikes" resultType="com.tedu.pojo.People">select ${columns} from people where name like '%${p_name}%'</select> <!-- 根据if标签进行条件查询 动态sql --> <select id="select_if" resultType="com.tedu.pojo.People"> select * from people <if test="p_name!=null">where name like '%${p_name}%'</if> </select> <!-- where和if标签结合使用 动态sql --> <select id="select_where_if" resultType="com.tedu.pojo.People"> select * from people <where> <if test="smallSalary!=null">salary>#{smallSalary}</if> <if test="bigSalary!=null">and salary<![CDATA[<]]>#{bigSalary} </if> </where> </select> <!-- set标签 动态sql --> <update id="update_set"> update people <set> <if test="home!=null">home=#{home} where name=#{name}</if> </set> </update> <!-- foreach遍历 item="ids"表示接收参数的变量 --> <update id="delete_array"> delete from people where id in <foreach collection="array" open="(" separator="," close=")" item="ids">#{ids}</foreach> </update> </mapper>- PeopleMapper.java
package com.tedu.dao; import java.util.List; import com.tedu.pojo.People; /** * 1,EmpMapper.xml对应的接口 * 2,接口中的方法名要和EmpMapper.xml中查询语句的id保持相同 * @author sujianda * */ public interface PeopleMapper { /** * 查询所有信息 */ public List<People> selectAll(); /** * 根据id查询某一个员工 */ public People selectOne(int id); }- MyBatisInterfaceTest测试类
package com.tedu.mybatis; import java.io.IOException; import java.io.InputStream; 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 org.junit.Test; import com.tedu.dao.PeopleMapper; import com.tedu.pojo.People; public class MyBatisInterfaceTest { public static void main(String[] args) throws IOException { //读取核心配置文件sqlMapConfig.xml,getResourceAsStream获取资源作为流 InputStream in=Resources.getResourceAsStream("sqlMapConfig.xml"); //通过配置信息获取SqlSessionFactory对象 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); //通过工厂获取SqlSession对象,session线程不安全 SqlSession session=factory.openSession(); //getMapper(EmpMapper.class)返回的是一个EmpMapper实例,得到empMapper实例之后,再调用selectAll PeopleMapper empMapper=session.getMapper(PeopleMapper.class); List<People>list=empMapper.selectAll(); //输出信息 for (People emp : list) { System.out.println(emp.toString()); } } @Test public void selectOne() throws IOException { InputStream in=Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); SqlSession session=factory.openSession(); PeopleMapper empMapper=session.getMapper(PeopleMapper.class); People emp=empMapper.selectOne(1); System.out.println(emp.toString()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。