mybatis入门实例

本文详细介绍了一个基于Maven、Eclipse、MyBatis和MySQL的Java项目搭建过程,包括环境配置、依赖引入、数据库设计、实体类创建、DAO接口定义、XML映射文件编写及测试类实现,展示了增删改查等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例代码:https://download.youkuaiyun.com/download/u010476739/11438497

试验环境:
maven3.6、eclipse、mybatis3.5.2、mysql5.7

1. 新建maven的jar工程

2. 建成后的工程目录:

3. 引入mybatis和mysql依赖:

最终pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jackletter</groupId>
	<artifactId>mybvaties-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.12</version>
		</dependency>

	</dependencies>
</project>

4. 准备数据库

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `birth` datetime DEFAULT NULL,
  `files` blob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

5. 完善代码和配置文件后的工程目录:

5.1 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>
	<!-- 指定properties配置文件, 我这里面配置的是数据库相关 -->
	<properties resource="db.properties"></properties>
	<typeAliases>
		<typeAlias alias="Test" type="com.jackletter.entity.Test" />
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>

	<!-- 映射文件,使用mapper单独引入,使用package定义扫描的包(注意xml和接口要在同一个包下且同名) -->
	<mappers>
		<mapper resource="com/jackletter/dao/TestDao.xml" />
		<!-- <package name="com.jackletter.dao" /> -->
	</mappers>

</configuration>

5.2 数据库配置文件:(db.properties)

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jujiao?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true
username=root
password=123456

5.3 实体类:Test.java

package com.jackletter.entity;

import java.util.Date;

public class Test {
	public int id;
	public String name;
	public int age;
	public Date birth;
	public byte[] files;
	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 Date getBirth() {
		return birth;
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public byte[] getFiles() {
		return files;
	}
	public void setFiles(byte[] files) {
		this.files = files;
	}
	@Override
	public String toString() {
		return "Test [id=" + id + ", name=" + name + ", age=" + age + ", birth=" + birth + ", files="
				+ new String(files) + "]";
	}	

}

5.4 dao接口:TestDao.java

package com.jackletter.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jackletter.entity.Test;

public interface TestDao {
	public Test findTestById(int id);

	public int insert(Test test);

	public int update(Test test);

	public int delete(int id);

	public List<Test> findTests(HashMap map);

	public Map findMap();
}

5.5 mybatissql语句配置:(TestDao.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="com.jackletter.dao.TestDao">

	<select id="findTestById" resultType="Test">
		select * from test where id
		= #{id}
	</select>
	<select id="findTests" resultType="Test"
		parameterType="java.util.Map">
		select * from test
		<where>
			<if test="name!=null">
				name like CONCAT('%',#{name},'%')
			</if>
			<if test="agemax!=null and agemax>=0">
				age &lt;= #{agemax}
			</if>
			<if test="agemin!=null and agemin>=0">
				age &gt;= #{agemin}
			</if>
		</where>
	</select>
	<select id="findMap" resultType="java.util.Map">
		select * from test limit 1
	</select>

	<insert id="insert" parameterType="Test" useGeneratedKeys="true"
		keyProperty="id" keyColumn="id">
		INSERT INTO
		test
		(name,age,birth,files)VALUES(#{name},#{age},#{birth},#{files})
	</insert>

	<update id="update" parameterType="Test">
		UPDATE test set
		name=#{name},age=#{age},birth=#{birth},files=#{files}
		WHERE id=#{id}
	</update>

	<update id="delete">
		create table tmp as select max(id) as id from test;
		delete from test where id = (select id from tmp);
		drop table tmp;
	</update>

</mapper>

5.6 测试类:App.java

package com.jackletter;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.Before;
import org.junit.Test;

import com.jackletter.dao.TestDao;

public class App {
	static SqlSessionFactory sqlSessionFactory;
	static SqlSession session;

	@Before
	public void Init() throws Exception {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		session = sqlSessionFactory.openSession();
	}

	@Test
	public void TestInsert() throws Exception {
		TestDao testMapper = session.getMapper(TestDao.class);
		// 插入
		com.jackletter.entity.Test model = new com.jackletter.entity.Test();
		model.setName("晓明");
		model.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse("1996-06-03"));
		model.setAge(25);
		model.setFiles("hello 你好".getBytes());
		int i = testMapper.insert(model);
		session.commit();
		System.out.println("插入数据量:" + i + "个,生成的ID:" + model.getId());
		model.setName("小红");
		model.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse("1996-06-03"));
		model.setAge(26);
		model.setFiles("hello 小红".getBytes());
		i = testMapper.insert(model);
		session.commit();
		System.out.println("插入数据量:" + i + "个,生成的ID:" + model.getId());
		
		model.setName("小刚");
		model.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse("1996-06-03"));
		model.setAge(25);
		model.setFiles("hello 小刚".getBytes());
		i = testMapper.insert(model);
		session.commit();
		System.out.println("插入数据量:" + i + "个,生成的ID:" + model.getId());
	}

	@Test
	public void TestQuery() {
		TestDao testMapper = session.getMapper(TestDao.class);
		// 查询
		com.jackletter.entity.Test test = testMapper.findTestById(1);
		System.out.println(test);
	}

	@Test
	public void TestUpdate() {
		TestDao testMapper = session.getMapper(TestDao.class);
		// 更新
		com.jackletter.entity.Test test = testMapper.findTestById(1);
		System.out.println(test);
		test.setName(test.getName() + (new Date()).getYear());
		int i = testMapper.update(test);
		session.commit();
		System.out.println("更新了数据:" + i + "个");
	}

	@Test
	public void TestDelete() {
		TestDao testMapper = session.getMapper(TestDao.class);
		// 刪除
		int i = testMapper.delete(1);
		session.commit();
		System.out.println("删除了数据:" + i + "个");
	}

	@Test
	public void TestQueryMap() throws Exception {
		try (SqlSession session = sqlSessionFactory.openSession()) {
			TestDao testMapper = session.getMapper(TestDao.class);
			HashMap map = new HashMap();
			map.put("name", "红");
			List<com.jackletter.entity.Test> tests = testMapper.findTests(map);
			System.out.println(tests);
		}
	}

	@Test
	public void TestFindMap() throws Exception {
		try (SqlSession session = sqlSessionFactory.openSession()) {
			TestDao testMapper = session.getMapper(TestDao.class);
			Map map = testMapper.findMap();
			System.out.println(map);
		}
	}
}

6. 测试运行

6.1 测试插入:

6.2 测试查询

6.3 测试更新

6.4 测试删除

6.5 测试条件化查询

6.6 测试查询结果为map

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackletter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值