pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.syh</groupId>
<artifactId>Mybatis01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties .xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!--配置文件的路径-->
<configurationFile>src/main/resources
/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
jdbc.properties 除pom.xml外的配置文件均在resources文件夹下创建
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456
log4j.properties
# Global logging configuration info warning error
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
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">
<!--mybatis全局配置文件:节点的顺序参考,按住ctrl+configuration进入文件查看-->
<configuration>
<properties resource="jdbc.properties"></properties>
<!--配置日志-->
<settings>
<setting name="logImpl" value="LOG4J"/>
<!--是否开启二级缓存,默认false不开启,true开启
<setting name="cacheEnabled" value="true"/>-->
</settings>
<!--设置别名-->
<typeAliases>
<!--<typeAlias type="com.syh.pojo.Team" alias="Team"></typeAlias>-->
<!--以整个包来设置,包里所有类的别名默认为类名(首字母大小写都可以)-->
<package name="com.syh.pojo"/>
<package name="com.syh.mapper"/>
</typeAliases>
<!--配置分页插件-->
<plugins>
<!--5.0版本之前使用PageHelper,之后使用PageInterceptor-->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--reasonable合理化,默认为false,小于第一页查询第一页,大于最后一页查询最后一页
<property name="reasonable" value="true"/>-->
</plugin>
</plugins>
<!--配置 mybatis 环境-->
<environments default="development">
<!--id:数据源的名称-->
<environment id="development">
<!--事务类型:使用 JDBC 事务,使用 Connection 的提交和回滚-->
<transactionManager type="JDBC"></transactionManager>
<!--数据源 dataSource:创建数据库 Connection 对象
type: POOLED 使用数据库的连接池
-->
<dataSource type="POOLED">
<!--连接数据库的四大参数
注意数据库版本使用的是MySQL8,如果是mysql5的话,driver和url都不一样,参考学过的JDBC-->
<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>
</environments>
<!--在配置文件中注册映射文件-->
<mappers>
<!--<mapper resource="com/syh/pojo/Team.xml"></mapper>-->
<package name="com.syh.pojo"/>
<package name="com.syh.mapper"/>
<package name="org.sss.pojo"/>
<package name="org.sss.mapper"/>
</mappers>
</configuration>
package com.syh.pojo;
import java.util.Date;
import java.util.List;
//球队的实体类:一方
public class Team {
private Integer teamId;
private String teamName;
private String location;
private Date createTime;
//关系字段:一方(球队)持有多方(球员)的集合
private List<Player> playerList1;
private List<Player> playerList2;
//testAdd方法需要重写toString
@Override
public String toString() {
return "Team{" +
"teamId=" + teamId +
", teamName='" + teamName + '\'' +
", location='" + location + '\'' +
", createTime=" + createTime +
", playerList1=" + playerList1 +
", playerList2=" + playerList2 +
'}';
}
//省略get/set方法
}
package com.syh.mapper;
import com.syh.pojo.QueryTeamVO;
import com.syh.pojo.QueryVO;
import com.syh.pojo.Team;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface TeamMapper {
List<Team> queryAll();
Team queryById(Integer teamId);
int add(Team team);
int update(Team team);
int delete(Integer teamId);
List<Team> queryRange1(Integer min,Integer max);
List<Team> queryRange2(@Param("min") Integer min, @Param("max")Integer max);
List<Team> queryRange3(Map<String,Object> map);
List<Team> queryByCondition(QueryVO vo);
List<Team> queryByFiled(@Param("column") String column,@Param("columnValue")String columnValue);
int getCount();
Map<String,Object> getTwoColumn();
List<Map<String,Object>> getTwoColumnList();
List<Team> queryAll2();
Team queryById1(Integer teamId);
Team queryById2(Integer teamId);
List<Team> queryVO(QueryTeamVO vo);
int update2(Team team);
void addList(List<Team> list);
void delList(List<Integer> teamId);
}
package com.syh.pojo;
//自定义封装的查询条件
public class QueryVO {
private String name;
private Integer min;
private Integer max;
private String location;
//省略get/set方法
}
package com.syh.pojo;
import java.util.Date;
//自定义封装的球队查询条件
public class QueryTeamVO {
private String name;
private Date beginTime;
private Date endTime;
private String location;
//省略get/set方法
}
TeamMapper.xml(必须与TeamMapper接口的路径包名保持一致,resources下创建com.syh.mapper)
<?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">
<!--映射文件 ORM思想 object relation mapping
将sql语句从代码的硬编码中抽取出来
-->
<!--namespace="接口的完全限定名"-->
<mapper namespace="com.syh.mapper.TeamMapper">
<!--id="自定义名称,id不能重复;相当于dao中的方法名称"
resultType="返回类型(输入映射),如果是集合则返回的对象
使用要求:实体类中的属性名与表中的列名一致"
在mybatis.xml中设置com.syh.pojo.Team的别名为Team
-->
<select id="queryAll" resultType="Team">
select * from team
</select>
<!--parameterType:参数类型,参数不为对象时可以省略,框架会自行判断
#{自定义参数名称} 没有实际的意义
-->
<select id="queryById" parameterType="java.lang.Integer" resultType="Team">
select * from team where teamId=#{id}
</select>
<!--parameterType:"com.syh.pojo.Team" 将对象作为参数
#{值} 必须是实体类中属性的名称
-->
<insert id="add" parameterType="Team">
<!--keyProperty:表示将新增的id赋值给属性teamId
order:BEFORE/AFTER 表示sql语句是在insert语句之前还是之后执行
-->
<selectKey keyProperty="teamId" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into team (teamName,location,createTime)
values (#{teamName},#{location},#{createTime})
</insert>
<update id="update" parameterType="Team">
update team set teamName=#{teamName},location=#{location}
where teamId=#{teamId}
</update>
<delete id="delete">
delete from team where teamId=#{id}
</delete>
<!--方式1
细节1.mybatis3.3之前可以直接写#{0} #{1}
从mybatis3.4开始:#{arg0} #{arg1}或者#{param1} #{param2}...(了解即可)
细节2.sql语句当中不能使用小于号,要通过转译符替代< 大于号无限制
-->
<select id="queryRange1" resultType="Team">
select * from team
where teamId>=#{arg0} and teamId<=#{arg1}
</select>
<!--方式2
#{}中的名称必须与方法接口中的参数注解@Param()中的名称保持一致(常用)
-->
<select id="queryRange2" resultType="Team">
select * from team
where teamId>=#{min} and teamId<=#{max}
</select>
<!--方式3
#{}中的名称必须与Map集合中的key保持一致
-->
<select id="queryRange3" resultType="Team">
select * from team
where teamId>=#{min} and teamId<=#{max}
</select>
<!--方式4
#{}中的名称必须与自定义封装类的属性保持一致
-->
<select id="queryByCondition" resultType="Team">
select * from team
where teamId>=#{min} and teamId<=#{max}
and teamName like #{name} and location=#{location}
</select>
<select id="queryByFiled" resultType="Team">
select * from team where ${column}=#{columnValue}
</select>
<!--要求返回值类型必须是单行单列,如果是单行多列无法取到后面的列值-->
<select id="getCount" resultType="java.lang.Integer">
select count(teamId) from team
</select>
<select id="getTwoColumn" resultType="java.util.HashMap">
select count(teamId),max(teamId) from team
</select>
<select id="getTwoColumnList" resultType="java.util.HashMap">
select count(teamId),max(teamId) from team group by location
</select>
<!--创建resultMap,相当于自己编写表中的列与实体类中的属性的映射
id:resultMap的名字,要求唯一
type:想要映射的类型
-->
<resultMap id="baseResultMap" type="Team">
<!--一般主键列用id,其余列用result
column:表示数据库表中的列名,不区分大小写
property:表示实体类中对象的属性名,区分大小写
javaType:表示实体类当中对应的属性类型,可以省略,mybatis会自行判断
-->
<id column="teamId" property="teamId" javaType="java.lang.Integer"></id>
<result column="teamName" property="teamName"></result>
<result column="location" property="location"></result>
<result column="createTime" property="createTime"></result>
</resultMap>
<!--resultMap和resultType不能同时出现
resultMap引用的是自己创建的id值
-->
<select id="queryAll2" resultMap="baseResultMap">
select * from team
</select>
<!--方式1-->
<select id="queryById1" resultMap="joinPlayerMap1">
select * from team t inner join player p
on t.teamId=p.teamId
where t.teamId=#{id}
</select>
<resultMap id="joinPlayerMap1" type="Team" extends="baseResultMap">
<!--collection:对多映射的节点
property:实体类中要查询的集合属性
javaType:集合类型
ofType:集合类型中的元素类型
-->
<collection property="playerList1" javaType="arraylist" ofType="Player"
resultMap="com.syh.mapper.PlayerMapper.baseResultMap"></collection>
</resultMap>
<select id="queryById2" resultMap="joinPlayerMap2">
select * from team where teamId=#{id}
</select>
<resultMap id="joinPlayerMap2" type="Team" extends="baseResultMap">
<collection property="playerList2" javaType="arraylist" ofType="Player" column="teamId"
select="com.syh.mapper.PlayerMapper.queryByTeamId"></collection>
</resultMap>
<select id="queryVO" parameterType="QueryVO" resultMap="baseResultMap">
select * from team
<where>
<!--模糊查询需要用concat函数-->
<if test="name!=null">
teamName like concat(concat('%',#{name}),'%')
</if>
<if test="beginTime!=null">
and createTime>=#{beginTime}
</if>
<if test="endTime!=null">
and createTime<=#{endTime}
</if>
<if test="location!=null">
and location=#{location}
</if>
</where>
</select>
<update id="update2" parameterType="Team">
update team
<set>
<if test="teamName!=null">
teamName=#{teamName},
</if>
<if test="location!=null">
location=#{location},
</if>
<if test="createTime!=null">
createTime=#{createTime},
</if>
</set>
where teamId=#{teamId}
</update>
<insert id="addList" parameterType="arraylist">
<!--批量添加-->
insert into team (teamName,location) values
<!--collection:要遍历的集合,参数是集合类型,直接写list
item:代表遍历的集合中的每一个数据
separator:将遍历的结果用逗号来分割
-->
<foreach collection="list" item="t" separator=",">
(#{t.teamName},#{t.location})
</foreach>
</insert>
<delete id="delList" parameterType="arraylist">
<!--批量删除-->
delete from team where teamId in
<!--open="(" close=")" 表示用()将拼接结果包裹起来-->
<foreach collection="list" item="teamId" separator="," open="(" close=")">
#{teamId}
</foreach>
</delete>
</mapper>
import com.syh.mapper.TeamMapper;
import com.syh.pojo.Team;
import com.syh.util.MyBatisUtil;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class TestTeamMapper {
//通过动态代理的方式创建实现类
private TeamMapper teamMapper = MyBatisUtil.getSqlSession().getMapper(TeamMapper.class);
@Test
public void testQueryById(){
Team team = teamMapper.queryById(101);
System.out.println(team);
}
@Test
public void testQueryAll(){
List<Team> list = teamMapper.queryAll();
for (Team team : list) {
System.out.println(team);
}
}
@Test
public void testAdd(){
Team team = new Team();
team.setTeamName("火箭");
team.setLocation("休斯顿");
team.setCreateTime(new Date());
int num = teamMapper.add(team);
//增删改需要手动提交数据
MyBatisUtil.getSqlSession().commit();
System.out.println("受影响的行数"+num);
System.out.println("球队新增的id值为"+team.getTeamId());
}
@Test
public void testUpdate(){
Team team = teamMapper.queryById(105);
team.setTeamName("小牛");
team.setLocation("达拉斯");
int num = teamMapper.update(team);
MyBatisUtil.getSqlSession().commit();
System.out.println(num);
}
@Test
public void testDel(){
int num = teamMapper.delete(105);
MyBatisUtil.getSqlSession().commit();
System.out.println(num);
}
}
package com.syh.util;
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 java.io.IOException;
import java.io.Reader;
//工具类
public class MyBatisUtil {
private static ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<>();
private static SqlSessionFactory factory;
static {
Reader reader = null;
try {
//读取配置文件
reader = Resources.getResourceAsReader("mybatis.xml");
} catch (IOException e) {
e.printStackTrace();
}
//创建工厂
factory = new SqlSessionFactoryBuilder().build(reader);
}
//获取连接
public static SqlSession getSqlSession() {
//从ThreadLocal中获取
SqlSession sqlSession = sqlSessionThreadLocal.get();
if (sqlSession == null) {
//创建sqlSession
sqlSession = factory.openSession();
//将sqlSession与线程进行绑定
sqlSessionThreadLocal.set(sqlSession);
}
return sqlSession;
}
//关闭连接
public static void closeSqlSession() {
SqlSession sqlSession = sqlSessionThreadLocal.get();
if (sqlSession != null) {
sqlSession.close();
sqlSessionThreadLocal.remove();
}
}
}
import java.util.ArrayList;
import java.util.List;
public class TestThreadLocal {
//一个类似于list集合的容器,但与list集合不同点在于只能存放一个数据
private ThreadLocal<String> threadLocal = new ThreadLocal<>();
private List<String> list = new ArrayList<>();
class Thread01 extends Thread{
@Override
public void run() {
threadLocal.set("王五");
list.add("赵六");
System.out.println("MyThread01---threadLocal---"+threadLocal.get());
System.out.println("MyThread01---list---"+list.get(0));
}
}
class Thread02 extends Thread{
@Override
public void run() {
threadLocal.set("王五2");
list.add("赵六2");
System.out.println("MyThread02---threadLocal---"+threadLocal.get());
System.out.println("MyThread02---list---"+list.get(1));
}
}
public static void main(String[] args) {
TestThreadLocal test = new TestThreadLocal();
Thread01 t1 = test.new Thread01();
Thread02 t2 = test.new Thread02();
t1.start();
t2.start();
}
/*public static void main(String[] args) {
TestThreadLocal test = new TestThreadLocal();
test.threadLocal.set("张三");
//再次添加会进行覆盖
test.threadLocal.set("李四");
String s = test.threadLocal.get();
System.out.println(s);
}*/
}
package com.syh.pojo;
//球员的实体类:多方
public class Player {
private Integer playerId;
private String playerName;
private Integer playerNum;
private Integer teamId;
//关系字段:多方(球员)持有一方(球队)的对象
private Team team1;
private Team team2;
private Team team3;
@Override
public String toString() {
return "Player{" +
"playerId=" + playerId +
", playerName='" + playerName + '\'' +
", playerNum=" + playerNum +
", teamId=" + teamId +
", team1=" + team1 +
", team2=" + team2 +
", team3=" + team3 +
'}';
}
//省略get/set方法
}
package com.syh.mapper;
import com.syh.pojo.Player;
import java.util.List;
public interface PlayerMapper {
Player queryById(int playerId);
Player queryById1(int playerId);
Player queryById2(int playerId);
Player queryById3(int playerId);
List<Player> queryByTeamId(int teamId);
}
PlayerMapper.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.syh.mapper.PlayerMapper">
<select id="queryById" resultMap="baseResultMap">
select * from player where playerId=#{id}
</select>
<resultMap id="baseResultMap" type="Player">
<id column="playerId" property="playerId"></id>
<result column="playerName" property="playerName"></result>
<result column="playerNum" property="playerNum"></result>
<result column="teamId" property="teamId"></result>
</resultMap>
<!--方式1.通过对象.属性直接映射列名(基本不用)
要求:必须连接查询(一般会自定义结果集)
-->
<select id="queryById1" resultMap="joinTeamResult1">
select * from player p inner join team t
on p.teamId=t.teamId
where playerId=#{id}
</select>
<resultMap id="joinTeamResult1" type="Player" extends="baseResultMap">
<result column="teamId" property="team1.teamId"></result>
<result column="teamName" property="team1.teamName"></result>
<result column="location" property="team1.location"></result>
<result column="createTime" property="team1.createTime"></result>
</resultMap>
<!--方式2.直接引用关联对象的Mapper映射
要求:必须连接查询(一般会自定义结果集)
-->
<select id="queryById2" resultMap="joinTeamResult2">
select * from player p inner join team t
on p.teamId=t.teamId
where playerId=#{id}
</select>
<resultMap id="joinTeamResult2" type="Player" extends="baseResultMap">
<!--association:对一映射的节点-->
<association property="team2" javaType="Team"
resultMap="com.syh.mapper.TeamMapper.baseResultMap"></association>
</resultMap>
<!--方式3.使用关联对象的单独查询语句
要求:需要关联对象中必须存在对应的查询语句(不再需要连接查询)
-->
<select id="queryById3" resultMap="joinTeamResult3">
select * from player where playerId=#{id}
</select>
<resultMap id="joinTeamResult3" type="Player" extends="baseResultMap">
<association property="team3" javaType="Team" column="teamId"
select="com.syh.mapper.TeamMapper.queryById"></association>
</resultMap>
<select id="queryByTeamId" resultMap="baseResultMap">
select * from player where teamId=#{id}
</select>
</mapper>
generatorConfig.xml 反向生成内容
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器:标了序号的部分都需要修改成自己的内容 -->
<generatorConfiguration>
<!--1、数据库驱动jar:添加自己的jar路径 -->
<classPathEntry
location="G:\Local repository\mysql\mysql-connector-java\8.0.23\mysql-connector-java-8.0.23.jar" />
<context id="MyBatis" targetRuntime="MyBatis3">
<!--去除注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--2、数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT"
userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer;
为true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--3、生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
使用Maven生成在target目录下,会自动创建) -->
<javaModelGenerator targetPackage="org.sss.pojo"
targetProject="src\main\java">
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--4、生成mapper.xml映射文件 -->
<sqlMapGenerator targetPackage="org.sss.mapper"
targetProject="src\main\resources">
</sqlMapGenerator>
<!--5、生成Dao(Mapper)接口文件 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="org.sss.mapper"
targetProject="src\main\java">
</javaClientGenerator>
<!--6、要生成哪些表(更改tableName和domainObjectName就可以) -->
<!-- tableName:要生成的表名
enableCountByExample:Count语句中加入where条件查询,默认为true开启
enableUpdateByExample:Update语句中加入where条件查询,默认为true开启
enableDeleteByExample:Delete语句中加入where条件查询,默认为true开启
enableSelectByExample:Select多条语句中加入where条件查询,默认为true开启
selectByExampleQueryId:Select单个对象语句中加入where条件查询,默认为true开启
-->
<!--<table tableName="Team"
enableCountByExample="false"
enableUpdateByExample="false"
enableUpdateByPrimaryKey="false"
enableDeleteByExample="false"
enableDeleteByPrimaryKey="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
<property name="useActualColumnNames" value="true"/>
</table>-->
<table tableName="Team">
<!--创建的列名需要符合java的命名规范,列名带有下划线就不需要设置-->
<property name="useActualColumnName" value="true"/>
</table>
<table tableName="Player">
<property name="useActualColumnName" value="true"/>
</table>
<table tableName="GameRecord">
<property name="useActualColumnName" value="true"/>
</table>
</context>
</generatorConfiguration>
Mybatis入门案例
于 2022-08-13 11:28:42 首次发布