Maven
介绍
是一个项目管理和构建工具
- 提供了一套标准化的项目结构
- 提供了一套标准化的构建流程(编译,测试,打包,发布……)
- 提供了一套依赖管理机制
注意使用和配置
Mybatis
1.作用
是一款优秀的持久层框架,用于简化 JDBC 开发,jdbc操作太过于繁琐
JavaEE三层架构:表现层、业务层、持久层
2.如何比JDBC简化
对于硬编码:注册驱动,获取连接,sql语句在Mybatis中可以配置到配置文件。
对于操作繁琐:封装结果集,手动设置参数在Mybatis中可以自动完成。
3.简单使用
3.1配置maven并安装依赖
<?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.javawebmaven</groupId>
<artifactId>javamaven</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
3.2新建logback.xml(日志)配置
<!-- 级别从高到低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则 根据当前ROOT 级别,日志输出时,级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志 -->
<!-- scan 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 -->
<!-- scanPeriod 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 动态日志级别 -->
<jmxConfigurator />
<!-- 定义日志文件 输出位置 -->
<!-- <property name="log_dir" value="C:/test" />-->
<property name="log_dir" value="./logs" />
<!-- 日志最大的历史 30天 -->
<property name="maxHistory" value="30" />
<!-- ConsoleAppender 控制台输出日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
<!-- 设置日志输出格式 -->
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
</pattern>
</encoder>
</appender>
<!-- ERROR级别日志 -->
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender -->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只记录WARN级别的日志 -->
<!-- 果日志级别等于配置级别,过滤器会根据onMath 和 onMismatch接收或拒绝日志。 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 设置过滤级别 -->
<level>ERROR</level>
<!-- 用于配置符合过滤条件的操作 -->
<onMatch>ACCEPT</onMatch>
<!-- 用于配置不符合过滤条件的操作 -->
<onMismatch>DENY</onMismatch>
</filter>
<!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>
${log_dir}/error/%d{yyyy-MM-dd}/error-log.log
</fileNamePattern>
<!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件假设设置每个月滚动,且<maxHistory>是6, 则只保存最近6个月的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>
<!-- 设置日志输出格式 -->
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n
</pattern>
</encoder>
</appender>
<!-- WARN级别日志 appender -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只记录WARN级别的日志 -->
<!-- 果日志级别等于配置级别,过滤器会根据onMath 和 onMismatch接收或拒绝日志。 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 设置过滤级别 -->
<level>WARN</level>
<!-- 用于配置符合过滤条件的操作 -->
<onMatch>ACCEPT</onMatch>
<!-- 用于配置不符合过滤条件的操作 -->
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>${log_dir}/warn/%d{yyyy-MM-dd}/warn-log.log</fileNamePattern>
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- INFO级别日志 appender -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/info/%d{yyyy-MM-dd}/info-log.log</fileNamePattern>
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- DEBUG级别日志 appender -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/debug/%d{yyyy-MM-dd}/debug-log.log</fileNamePattern>
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- TRACE级别日志 appender -->
<appender name="TRACE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>TRACE</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_dir}/trace/%d{yyyy-MM-dd}/trace-log.log</fileNamePattern>
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- root级别 DEBUG -->
<root>
<!-- 打印debug级别日志及以上级别日志 -->
<level value="debug" />
<!-- 控制台输出 -->
<appender-ref ref="console" />
<!-- 文件输出 -->
<appender-ref ref="ERROR" />
<appender-ref ref="INFO" />
<appender-ref ref="WARN" />
<appender-ref ref="DEBUG" />
<appender-ref ref="TRACE" />
</root>
</configuration>
3.3新建UserMApper.xml(sql)并配置
<?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="test">
<select id="selectAll" resultType="com.javawebmaven.User">
select * from student;
</select>
</mapper>
3.4新建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>
<typeAliases>
<package name="com.javawebmaven"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
3.5创建User类(对象)
package com.javawebmaven;
public class User {
int id;
String name;
java.sql.Date birthday;
double score;
String email;
String tel;
int stutus;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", birthday=" + birthday +
", score=" + score +
", email='" + email + '\'' +
", tel='" + tel + '\'' +
", stutus=" + stutus +
'}';
}
}
3.6创建MybatisDemo类(查询数据)
package com.javawebmaven;
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.InputStream;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//
// //2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// //3. 执行sql
List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
for (User user : users) {
System.out.println(user);
}
// //4. 释放资源
sqlSession.close();
}
}
4.修改,使用Mapper代理
4.1原因
// //3. 执行sql
List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字
在我们使用中需要传参,有硬编码问题,所以使用Mapper代理解决
UserMApper userMapper=sqlSession.getMapper(UserMapper.class);
List<User> user = userMapper.selectAll();
4.2修改之后代码:
UserMapper.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.maper.UserMapper">
<select id="selectAll" resultType="com.javawebmaven.User">
select * from student;
</select>
</mapper>
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>
<typeAliases>
<package name="com.javawebmaven"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<!--<mapper resource="UserMapper.xml"/>-->
<mapper resource="go/UserMapper.xml"></mapper>
</mappers>
</configuration>
MyBatisDemo修改
package com.javawebmaven;
import com.maper.UserMapper;
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.InputStream;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//
// //2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// //3. 执行sql
// List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
//3.1 获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
for (User user : users) {
System.out.println(user);
}
// //4. 释放资源
sqlSession.close();
}
}
新建接口UserMapper
package com.maper;
import com.javawebmaven.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
User selectById(int id);
}
5.注意
1.数据没有收集全部
2.占位符#{}对应perpreStatment和${}对应statment
3.对应特殊字符的转义:
> 的转义:< 或者 ]]>
4.多条件和单条件引入sql动态查询:if,choose(when,otherwise),trim,foreach等标签
5.对应多个参数使用注解@Param可以提高代码可读性
6.使用注解:@select,@delect,@insert,@update
6.实现增删改查
UserMapper.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.maper.UserMapper">
<resultMap id="UserResultMap" type="User">
<!--
id:完成主键字段的映射
column:表的列名
property:实体类的属性名
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
<result column="status" property="stutus"/>
</resultMap>
<!--1.查询所有信息-->
<!--使用resultMap,给字段其别名(再此处,我的User类和Mysql的字段是完全一致的,所以没有修改),解决数据获取不完全问题-->
<select id="selectAll" resultMap="UserResultMap">
select * from student;
</select>
<!--<select id="selectAll" resultType="User">-->
<!--select * from student;-->
<!--</select>-->
<!--2. 查询详情-->
<!--使用#{PreparedStatement},或者${Statement}(St)解决占位问题-->
<select id="selectById" resultMap="UserResultMap">
select * from Student where id = #{id};
</select>
<select id="selectDYById" resultMap="UserResultMap">
select * from Student where id <![CDATA[
>
]]> #{id};
</select>
<select id="selectDTJById" resultMap="UserResultMap">
select *
from Student
where id = #{id}
and status = #{stutus}
and name= #{name};
</select>
<select id="selectDTByID" resultMap="UserResultMap">
select
*
from Student
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="stutus != null">
and status = #{stutus}
</if>
<if test="name != null">
and name like #{name}
</if>
</where>
</select>
<select id="selectChooseById" resultType="com.javawebmaven.User">
select
*
from Student
<where>
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="stutus != null">
and status = #{stutus}
</when>
<when test="name != null">
and name like #{name}
</when>
</choose>
</where>
</select>
<!--3.插入数据-->
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into student
(id,name,birthday,score,email,tel,status)
values
(#{id},#{name},#{birthday},#{score},#{email},#{tel},#{stutus});
</insert>
<!--4.修改数据-->
<update id="update">
update student
<set>
<if test="score != null">
score = #{score},
</if>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="birthday != null">
birthday = #{birthday},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
<if test="tel != null and tel != ''">
tel = #{tel},
</if>
<if test="stutus != null and stutus != ''">
status = #{stutus}
</if>
</set>
where id = #{id};
</update>
<!--5.删除数据-->
<delete id="deleteById">
delete from student where id =#{id}
</delete>
<delete id="deleteDTById">
delete from student where id
in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
</mapper>
UserMapper:
package com.maper;
import com.javawebmaven.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
// 查询所有信息
List<User> selectAll();
// 查询详情
List<User> selectById(int id);
List<User> selectDYById(int id);
List<User> selectDTJById(@Param("id") int id,@Param("status") int stutus,@Param("name") String name);
List<User> selectDTByID(User user);
List<User> selectChooseById(@Param("id") int id,@Param("status") int stutus,@Param("name") String name);
void add(User user);
void update(User user);
void deleteById(int id);
void deleteDTById(int[] ids);
}
MyBatisDemo:
package com.javawebmaven;
import com.maper.UserMapper;
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.InputStream;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
public class MyBatisDemo {
public static void main(String[] args) throws IOException, ParseException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//
// //2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// //3. 执行sql
// List<User> users = sqlSession.selectList("test.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
//3 获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//
//// 4.1执行sql,查询所有信息
// List<User> users = userMapper.selectAll();
// for (User user : users) {
// System.out.println(user);
// }
//
//
//
//
//// 4.2执行sql,查询id=2021的数据
// List<User> user1 = userMapper.selectById(2021);
// for (User user : user1) {
// System.out.println(user);
// }
//// 4.2执行sql,查询id>2021的name,id
// List<User> user2 = userMapper.selectDYById(2021);
// for (User user : user2) {
// System.out.println(user);
// }
//// 4.2执行sql,多条件查询id=2022并且name="wjc3"并且status=1
// List<User> user3 = userMapper.selectDTJById(2022,0,"wjc3");
// for (User user : user3) {
// System.out.println(user);
// }
//// 4.2执行动态sql,进行多条件查询
// String name="3";
// name="%"+name+"%";
// User user = new User();
// user.setId(2022);
// user.setStutus(0);
// user.setName(name);
// System.out.println(user);
// List<User> user4 = userMapper.selectDTByID(user);
// for (User user0 : user4) {
// System.out.println(user0);
// }
// 4.2单条件查询
// List<User> user5 = userMapper.selectChooseById(2022,0,"wjc3");
// for (User user0 : user5) {
// System.out.println(user0);
// }
// 4.3插入数据
String stringDate="2024-01-01";
Date date = new Date(new SimpleDateFormat("yyyy-MM-dd").parse(stringDate).getTime());
User user6 = new User(100,"王纪春",date,190.5,"1528.com","1569-15558",0);
// userMapper.add(user6);
//
//
//
// 4.4修改数据
User user9 = new User();
user9.setStutus(10);
user9.setScore(120.0);
user9.setName("wjc12");
user9.setEmail("4586.com");
user9.setTel("15258-9888");
user9.setBirthday(date);
user9.setId(100);
System.out.println(user6);
userMapper.update(user9);
// 4.5删除一行数据
userMapper.deleteById(100);
// 4.5删除多行数据
int[] ids = {2020,2029};
userMapper.deleteDTById(ids);
// 查询所有
List<User> users7 = userMapper.selectAll();
for (User u7 : users7) {
System.out.println(u7);
}
// //5. 释放资源
sqlSession.close();
}
}