mybatis的一些基础操作
MyBatis简介
百度上面有。这里不多说。MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射…
需要配置什么?
MyBatis首先需要配置jar包。
mybatis-3.5.2.jar
如果是MySQL,还需要一个mysql的jar包
mysql-connector-java-5.1.7-bin.jar
如果要输入打印日志,需要一个log4j.jar,还需要配置 log4j.properties
log4j-1.2.17.jar
如果需要用到json格式,还需要一个json格式的jar包
json-org-build20180908.jar
我给大家个下载链接 百度云的:
链接:https://pan.baidu.com/s/16b5SaYk0DvCYUXAqwwskXg
提取码:dov2
如果是SpringBoot下配置pom.xml文件就行了
<!-- 添加mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- 添加 FastJSON依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
在src目录下配置 mybatis-config.xml 文件
或者在根目录下
以下是MySQL数据库的配置,不过大径相同
<?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"/>
<property name="url" value="jdbc:mysql://127.0.0.1/xxx数据库?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="xxx数据库名字"/>
<property name="password" value="xxx数据库密码"/>
</dataSource>
</environment>
</environments>
<!-- 需要映射的目录,可以映射多个目录,不会互相干扰 -->
<mappers>
<mapper resource="mybatis-mapper.xml"/>
<!--
<mapper resource="mybatis-mapper-teachers.xml"/>
-->
</mappers>
</configuration>
下面配置 映射中的 mybatis-mapper.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="af.test">
<!-- 自定义映射 id是主键,result是列名映射 -->
<resultMap type="my.Teacher" id="teacherMapping">
<id property="id" column="id" />
<result property="name" column="姓名" />
<result property="subject" column="科目" />
</resultMap>
<!-- 在查询时,使用自定义映射 -->
<select id="selectTeacher" resultMap="teacherMapping">
select * from teacher
</select>
<!-- 同理id是自己命名,resultType是返回的数据类型,也可以是hashmap,也可以是自定义类型 -->
<select id="selectStudent" resultType="my.Student">
select * from student WHERE id = #{id}
</select>
<!-- > 相当于 great than,>的意思。 %lt; 相当于 lower than, <的意思 -->
<select id="getStudent7" resultType="my.Student">
select * from student where id >= #{from} AND id <= #{to}
</select>
</mapper>
xml的配置基本就这些了,然后说到怎么使用这些配置了
在程序中使用MyBatis
查询功能
首先要创建一个工厂SqlSessionFactory,我有许多实例,看己所需,代码如下:
//查询一条记录
public static void test1() throws Exception
{
//创建 SqlSessionFactory, resource的路径就首先配置src下的mybatis-config.xml
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream);
try(SqlSession session = sqlSessionFactory.openSession()) {
/*
这里的 test.getStudent 的就是配置 <mapper resource="mybatis-mapper.xml"/>的mybatis-mapper.xml
文件你命名的 namespace 和 需要用到的 select 查询的 id。合起来就是 namespace.id
*/
Student row = session.selectOne("af.test.getStudent", 20190005);
if(row != null)
System.out.println(row.id + "," + row.name + "," + row.sex + "," + row.cellphone);
}
}
//查询多条记录
public static void test2() throws Exception
{
//创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
List<Student> rows = session.selectList("af.test.getStudent2", 0);
System.out.println("共有记录:" + rows.size());
}
}
//指定了参数查询
public static void test3() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
List<Student> rows = session.selectList("af.test.getStudent3");
System.out.println("共有记录:" + rows.size());
}
}
//需要多个参数查询 就用model来传参数
public static void test4() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
Map<String, Object> model = new HashMap<>();
model.put("sex", 0);
model.put("name", "%吴%");
List<Student> rows = session.selectList("af.test.getStudent4",model);
for(int i=0; i<rows.size(); i++)
{
Student row = rows.get(i);
System.out.println(row.id + "," + row.name + "," + row.sex + "," + row.cellphone);
}
// System.out.println("共有记录:" + rows.size());
}
}
//返回单个 Map 记录,mybatis-mapper.xml返回值是 hashmap
public static void test5() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
Map row = session.selectOne("af.test.getStudent5", 20190001);
System.out.println(row.get("name"));
}
}
//返回多个 Map 记录
public static void test6() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
List<Map> row = session.selectList("af.test.getStudent6", 1);
System.out.println("test6共有记录:" + row.size());
}
}
//返回多个 Map 记录
public static void test7() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
try(SqlSession session = sqlSessionFactory.openSession()) {
List<Map> row = session.selectList("af.test.getStudent6", 1);
for(Map s : row)
{
System.out.println(s.get("id") + ":" + s.get("name"));
}
}
}
// 比较 大小 > > < <
public static void test8() throws Exception
{
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(stream);
Map<String, Object> model = new HashMap<>();
model.put("from", 20190001);
model.put("to", 20190003);
try(SqlSession session = sqlSessionFactory.openSession()) {
List<Student> row = session.selectList("af.test.getStudent7", model);
for(Student s : row)
{
System.out.println(s.id + ":" + s.name);
}
}
}
插入功能
插入数据的 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="af.test">
<!-- 插入数据操作 parameterType输入的数据类型 可以是pojo,也可以是hashmap等 -->
<insert id="insertStudent" parameterType="my.Student">
insert into student (id,name,sex,cellphone)
values (#{id}, #{name}, #{sex}, #{cellphone} )
</insert>
<insert id="insertStudent2" parameterType="hashmap">
insert into student (id,name,sex,cellphone)
values (#{id}, #{name}, #{sex}, #{cellphone} )
</insert>
<!-- 插入数据操作, useGeneratedKeys是否有自增主键,keyProperty是自增主键 -->
<insert id="insertTopic" parameterType="my.Topic"
useGeneratedKeys="true"
keyProperty="id" >
insert into topic(id, title, content, numView, timeCreated)
values( #{id}, #{title}, #{content}, #{numView}, #{timeCreated} )
</insert>
</mapper>
插入数据的代码实现
//使用pojo类插入一条记录
public static void test1() throws Exception
{
// 创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 不需要指定参数的情况
try(SqlSession session = sqlSessionFactory.openSession()) {
Student stu = new Student();
stu.id = 20190201;
stu.name = "张三";
stu.sex = true;
stu.cellphone = "12345678901";
session.insert("af.test.insertStudent", stu);
session.commit(); // 因为默认开启了事务,所以要commit()一下
}
}
//使用 map 插入一条记录
public static void test2() throws Exception
{
// 创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 不需要指定参数的情况
try(SqlSession session = sqlSessionFactory.openSession()) {
Map<String, Object> stu = new HashMap<>();
stu.put("id", 20190202);
stu.put("name", "袈裟");
stu.put("sex", false);
stu.put("cellphone", "12345678901");
session.insert("af.test.insertStudent2", stu);
session.commit(); // 因为默认开启了事务,所以要commit()一下
}
}
//使用 自增主键 返回自增主键
public static void test3() throws Exception
{
// 创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 不需要指定参数的情况
try(SqlSession session = sqlSessionFactory.openSession()) {
Topic row = new Topic();
row.setTitle("江山定");
row.setContent("风雨遮前路,冰火伴我行。一度波澜惊,而今江山定。");
row.setNumView(1230230);
row.setTimeCreated(null);
session.insert("af.test.insertTopic", row);
System.out.println("新纪录的ID:" + row.getId());
session.commit(); // 因为默认开启了事务,所以要commit()一下
}
}
更新与删除差不多
更新与删除的mybatis-mapper.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="af.test">
<!-- 更新 -->
<update id="updateStudent" parameterType="hashmap">
update student set cellphone=#{cellphone} where id=#{id}
</update>
<!-- 删除 -->
<delete id="deleteStudent" parameterType="hashmap">
delete from student where sex=#{sex}
</delete>
</mapper>
代码实现
//修改数据
public static void test1() throws Exception
{
// 创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 不需要指定参数的情况
try(SqlSession session = sqlSessionFactory.openSession()) {
HashMap<String,Object> map = new HashMap<>();
map.put("id", 20190001);
map.put("cellphone", "13810012388");
int affectedRows = session.update("af.test.updateStudent", map);
System.out.println("受影响的行数: " + affectedRows);
session.commit(); // 因为默认开启了事务,所以要commit()一下
}
}
//删除数据
public static void test2() throws Exception
{
// 创建 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 不需要指定参数的情况
try(SqlSession session = sqlSessionFactory.openSession()) {
HashMap<String,Object> map = new HashMap<>();
map.put("sex", 1);
int affectedRows = session.update("af.test.deleteStudent", map);
System.out.println("受影响的行数: " + affectedRows);
session.commit(); // 因为默认开启了事务,所以要commit()一下
}
}
这篇暂时就这样了