1.项目结构
开发工具:IDEA + Maven
项目结构图:
2.配置
2.1.Maven配置
Maven配置文件pom.xml,增加Mysql、Mybatis和Log4j2依赖包
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.poiuy</groupId>
<artifactId>mybatis-intro</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>org.poiuy</groupId>
<artifactId>mybatis-intro-sqlsession</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mybatis-intro-sqlsession-invoke Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
<!-- 数据库驱动类库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
<build>
<finalName>mybatis-intro-sqlsession</finalName>
</build>
</project>
2.2.Log4j2配置
Log4j2日志框架配置文件log4j2.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration status="error">
<!--定义所有的appender-->
<appenders>
<!--控制台输出-->
<Console name="Console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
<!--日志输出格式-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</Console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
<!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
<File name="log" fileName="D:/logs/log4j2.log" append="false">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
<!--添加过滤器ThresholdFilter,可以有选择的输出某个级别以上的类别 onMatch="ACCEPT" onMismatch="DENY"意思是匹配就接受,否则直接拒绝 -->
<File name="ERROR" fileName="D:/logs/error.log">
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
<!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
<RollingFile name="RollingFile" fileName="D:/logs/web.log"
filePattern="logs/${date:yyyy-MM}/web-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
<SizeBasedTriggeringPolicy size="2MB"/>
</RollingFile>
</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
<loggers>
<root level="trace">
<appender-ref ref="RollingFile"/>
<appender-ref ref="Console"/>
<appender-ref ref="ERROR" />
<appender-ref ref="log"/>
</root>
</loggers>
</configuration>
2.3.Mybatis配置
Mybatis配置文件mybatis_config.xml,设置日志输出为LOG4J2,并配置了数据库连接信息和Mapper文件路径
<?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>
<settings>
<setting name="logImpl" value="LOG4J2"/>
</settings>
<environments default="development">
<!--配置多个数据源-->
<environment id="development">
<!--事务提交方式:JDBC 利用JDBC方式处理事务
MANAGED 将事务交由其他组件托管-->
<transactionManager type="JDBC"/>
<!--数据源类型:POOLED 数据库连接池
UNNPOOLED 传统的JDBC模式
JNDI 从Tomcat中获取一个内置的数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.245.128:9906/poiuy_study"/>
<property name="username" value="root"/>
<property name="password" value="llian207"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.DAO层开发
DAO层只要编写Mapper文件即可,xml文件中定义了一系列方法,可供SqlSession调用
<?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,namespace的值习惯上设置成包 名+sql映射文件名,这样就能够保证namespace的值是唯一的 -->
<mapper namespace="org.poiuy.mybatis.intro.sqlsession.invoke.mapper.UserMapper">
<!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser, id属性值必须是唯一的,不能够重复 使用parameterType属性指明查询时使用
的参数类型,resultType属性指明查询返回的结果集类型 resultType="me.gacl.domain.User" 就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类 -->
<!-- 根据id删除一个user对象 -->
<delete id="deleteUser" parameterType="int">
DELETE FROM mybatis_user WHERE id=#{id}
</delete>
<!-- 插入 -->
<insert id="insertUser" parameterType="org.poiuy.mybatis.intro.sqlsession.invoke.domain.MybatisUser">
insert into mybatis_user(username,passwords,age,brith,email)
value(#{username}, #{passwords},#{age}, #{brith}, #{email})
</insert>
<!-- 根据id更新一个user对象 -->
<delete id="updateUser" parameterType="org.poiuy.mybatis.intro.sqlsession.invoke.domain.MybatisUser">
update mybatis_user set username=#{username}, passwords=#{passwords},
age=#{age},brith=#{brith}, email=#{email} WHERE id=#{id}
</delete>
<!-- 根据id查询得到一个user对象 -->
<select id="getUser" parameterType="int" resultType="org.poiuy.mybatis.intro.sqlsession.invoke.domain.MybatisUser">
select * from mybatis_user where id=#{id}
</select>
<resultMap type="org.poiuy.mybatis.intro.sqlsession.invoke.domain.MybatisUser" id="BaseResultMap" >
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="passwords" property="passwords"/>
<result column="age" property="age"/>
<result column="brith" property="brith"/>
<result column="email" property="email"/>
</resultMap>
<select id="getAllUser" resultMap="BaseResultMap">
select * from mybatis_user
</select>
<select id="getLimitUser" resultMap="BaseResultMap" parameterType="org.poiuy.mybatis.intro.sqlsession.invoke.domain.PageParam">
select * from mybatis_user limit #{offset},#{pagesize}
</select>
</mapper>
4.Domain开发
添加实体类对应数据表中的字段
package org.poiuy.mybatis.intro.sqlsession.invoke.domain;
import java.util.Date;
public class MybatisUser {
private int id;
private String username;
private String passwords;
private int age;
private Date brith;
private String email;
public MybatisUser() {
}
public MybatisUser(int id, String username, String passwords, int age, Date brith, String email) {
super();
this.id = id;
this.username = username;
this.passwords = passwords;
this.age = age;
this.brith = brith;
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", passwords=" + passwords + ","
+ " age=" + age + ", brith=" + brith + ", email=" + email + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswords() {
return passwords;
}
public void setPasswords(String password) {
this.passwords = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBrith() {
return brith;
}
public void setBrith(Date brith) {
this.brith = brith;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
5.Mybatis开发
开发步骤如下:
- 使用Resources加载配置文件
- 创建SqlSessionFactoryBuilder对象
- 使用SqlSessionFactoryBuilder创建SqlSessionFactory
- 使用SqlSessionFactory创建SqlSession
- 通过SqlSession调用Mapper方法
public static void main(String[] args) {
String resources = "mybatis/mybatis_config.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Application.class.getClassLoader().getResourceAsStream(resources);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
for(int i = 0; i < 10;i++){
insert(session);
}
selectOne(session);
update(session);
delete(session);
}
调用Mapper方法时,指定statement为Mapper文件的namespace.id即可,如果有参数就在方法中进行传递
public static void insert(SqlSession session) {
String dateStr = "2001/03/07";
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = null;
try {
date = format.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MybatisUser user = new MybatisUser(2,"张三","123456",23,date,"www.fail@126.com");
String statement = "org.poiuy.mybatis.intro.sqlsession.invoke.mapper.UserMapper.insertUser";
int count = session.insert(statement, user);
session.commit();
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/8257.html