什么是 MyBatis?
怎么获得Mybatis?
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
持久化
持久层
为什么使用Mybatis?
搭建环境
在resource目录创建Mybatis配置文件:mybatis-config.xml
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://localhost:3306/jdbc_test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="cn/cnyasin/dao/UserMapper.xml"/>
mappers>
configuration>
创建自己的一个Mybatis工具类:package cn.cnyasin.utils;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
private static String resource = "mybatis-config.xml";
private static InputStream inputStream = null;
/**
* 从 XML 中构建 SqlSessionFactory
*/
static {
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 从 SqlSessionFactory 中获取 SqlSession
* @return SqlSession
*/
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
创建pojo
public class User {
private int id;
private String username;
private String email;
private String password;
private long balance;
private long created_at;
// ...
}
在pom.xml中开启java目录资源过滤,Mybatis读取Mapper.xml需要该配置
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
注意:
src/main/resources
、src/main/java
两个都要打开,resources如果不配置默认只开启src/main/resources
目录,反之,如果配置了就会覆盖默认值。
注意:如果需要读取xml配置就开启
**/*.xml
,如果你需要读取properties配置就开启**/*.properties
。
创建dao:package cn.cnyasin.dao;
public interface UserMapper {
// 查询一个用户
User getOne(@Param("id") int id);
// 查询所有用户
List<User> getAll();
// 添加一个用户
int addOne(User user);
// 修改一个用户
int updateOne(User user);
// 删除一个用户
int deleteOne(int id);
}
创建Mapper:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.cnyasin.dao.UserMapper">
<select id="getOne" resultType="cn.cnyasin.pojo.User">
select * from user where id = #{id}
select>
<select id="getAll" resultMap="userListMap">
select * from user
select>
<insert id="addOne" parameterType="cn.cnyasin.pojo.User">
insert into user (`username`,`email`,`password`,`created_at`) values (#{username}, #{email}, #{password}, #{created_at})
insert>
<update id="updateOne" parameterType="cn.cnyasin.pojo.User">
update user set balance = #{balance} where id = #{id};
update>
<delete id="deleteOne">
delete from user where id = #{id}
delete>
<resultMap id="userListMap" type="cn.cnyasin.pojo.User"/>
mapper>
测试
@Test
public void getOneTest()
{
// 获取SQLSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
// getMapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getOne(1);
System.out.println(user);
System.out.println("----------------------------");
List<User> users = userMapper.getAll();
for (User user1 : users) {
System.out.println(user1);
}
// 关闭SQLSession
sqlSession.close();
}
@Test
public void updateOneTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getOne(6);
if (null == user) {
System.out.println("用户不存在。。。");
return;
}
user.setBalance(user.getBalance() + 100000);
int updateOne = mapper.updateOne(user);
if (updateOne > 0) {
System.out.println("用户余额更新成功。。。");
}
sqlSession.commit();
sqlSession.close();
}
// 增加、删除的测试方法省略。。。
The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone. ...
<property name="url" value="jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 113; 对实体 "characterEncoding" 的引用必须以 ';' 分隔符结尾。...
&
->&
),properties配置文件则不需要(&
)。&
改成&
,properties配置中则相反。The error may exist in cn/cnyasin/dao/UserMapper.xml...
原因分析:Maven资源过滤问题。Maven默认资源过滤文件目录为resources目录,java目录下的文件是不会被导出的,需要手动开启该目录的资源过滤。
解决方案:在pom.xml中添加如下代码:
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
注意:
src/main/resources
、src/main/java
两个都要打开,resources如果不配置默认只开启src/main/resources
目录,反之,如果配置了就会覆盖默认值。
注意:如果需要读取xml配置就开启
**/*.xml
,如果你需要读取properties配置就开启**/*.properties
。
value=%张三%
select * from user where name like "%"#{value}"%"
<typeAliases>
<typeAlias type="cn.cnyasin.pojo.User" alias="user"/>
typeAliases>
cn.cnyasin.pojo
中的JavaBean,在没有注解的情况下,会使用Bean的首字母小写的非限定类名来作为它的别名。若有注解,则别名为其注解值。<typeAliases>
<package name="cn.cnyasin.pojo"/>
typeAliases>
@Alias("user001")
public class User {}
<resultMap id="userListMap" type="user">
<result column="created_at" property="createdAt"/>
resultMap>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
log4j
log4j
1.2.17
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/logs.txt
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
public class UserMapperTest {
private static Logger logger = Logger.getLogger(UserMapperTest.class);
@Test
public void log4jTest() {
// 错误级别:debug < info < warn < error,级别越低输出的日志越详细
logger.debug("hahaha...呵呵。。。");
logger.info("hahaha...呵呵。。。");
logger.warn("hahaha...呵呵。。。");
logger.error("hahaha...呵呵。。。");
}
}
@Param()
注解。public interface UserMapper {
@Select("select * from user where id = #{id}")
User getOne(int id);
}
<mappers>
<mapper class="cn.cnyasin.dao.UserMapper"/>
mappers>
lombok
进行安装,然后按提示会让你重启idea,重启后默认开启该插件支持,要关闭可以再次打开idea的插件设置项,找到installed,禁用或者卸载。
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
@ExtensionMethod (Experimental, activate manually in plugin settings)
属性列表
其他常用属性
具体实现核心代码
update user
`username` = #{username}
`email` = #{email}
`password` = #{password}
`balance` = #{balance}
where id = #{id}
`username` = #{username}
and `email` = #{email}
and `password` = #{password}
and id in
#{id}