mybatis学习一之入门示例

-->

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>

代码:


定义pojo:

package com.zy.entity;

import lombok.Builder;

import lombok.Getter;

import lombok.Setter;

import lombok.ToString;

@Getter

@Setter

@ToString

@Builder(toBuilder = true)

public class Blog {

private Integer id;

private String title;

private int authorId;

private String state;

private Boolean featured;

private String style;

}

Mapper文件:


<?xml version="1.0" encoding="UTF-8" ?>

select * from Blog where id = #{id}

insert into Blog(id, title, author_id, state, featured, style)

values

(#{id}, #{title}, #{authorId}, #{state}, #{featured}, #{style});

定义接口:


package com.zy.mapper;

import com.huawei.entity.Blog;

public interface BlogMapper {

//接口中的方法名必须和mapper中sql语句的id相同

Blog selectBlog(Integer id);

//插入

void insert(Blog blog);

}

对应的类型:

定义DAO:


import com.huawei.entity.Blog;

import com.huawei.mapper.BlogMapper;

import com.huawei.util.MyBatisUtil;

import org.apache.ibatis.session.SqlSession;

public class BlogDao {

private SqlSession sqlSession = MyBatisUtil.getSqlSession();

private BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

public Blog queryBlogById(Integer id) {

return mapper.selectBlog(id);

}

public void insert(Blog blog) {

try {

mapper.insert(blog);

sqlSession.commit();

} finally {

if (sqlSession != null) {

sqlSession.close();

}

}

}

}

工具类的编写:


package com.zy.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 SqlSessionFactory sqlSessionFactory = null;

static {

try {

Reader reader = Resources.getResourceAsReader(“mybatis/mybatis-config.xml”);

sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

}

catch (IOException e) {

e.printStackTrace();

}

}

public MyBatisUtil() {

}

public static SqlSession getSqlSession() {

return sqlSessionFactory.openSession();

}

}

编写测试类:


package com.zy.mapper;

import com.huawei.dao.BlogDao;

import com.huawei.entity.Blog;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.junit.Test;

public class BlogMapperTest {

private static final Logger logger = LogManager.getLogger(BlogMapperTest.class);

@Test

public void testSelectBlog() {

Blog blog = new BlogDao().queryBlogById(1);

System.out.println(blog);

logger.info(“blog is:{}”, blog);

}

@Test

public void testInsertBlog() {

Blog build = Blog.builder()

.authorId(1)

.state(“ACTIVE”)

.style(“333”)

.featured(false)

.title(“三国演义”)

.build();

new BlogDao().insert(build);

}

}

运行结果:


问题:


1.为什么代码中的sqlSession需要关闭,但是获取配置文件的Reader不需要关闭呢???

看源码:

查看build()方法:

public SqlSessionFactory build(Reader reader) {

return this.build((Reader)reader, (String)null, (Properties)null);

}

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {

SqlSessionFactory var5;

try {

XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

var5 = this.build(parser.parse());

} catch (Exception var14) {

throw ExceptionFactory.wrapException(“Error building SqlSession.”, var14);

} finally {

ErrorContext.instance().reset();

try {

reader.close();

} catch (IOException var13) {

}

}

return var5;

}

我们发现,reader已经被关闭,因此不需要我们关闭

2.为什么插入数据时,需要手动提交呢???难道不能自动提交吗???

查看SqlSession的创建过程:

sqlSession = sqlSessionFactory.openSession();

进入DefaultSqlSessionFactory:

public SqlSession openSession() {

return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);

}

我们发现最后一个参数时false,这个参数时干嘛呢???继续往下看

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {

Transaction tx = null;

DefaultSqlSession var8;

try {

Environment environment = this.configuration.getEnvironment();

TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);

tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);

Executor executor = this.configuration.newExecutor(tx, execType);

var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);

} catch (Exception var12) {

this.closeTransaction(tx);

throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);

} finally {

ErrorContext.instance().reset();

}

return var8;

}

这个参数,其实就是autoCommit的参数,默认是false,表示不能自动提交,必须手动提交。

那么有没有支持传值的函数呢???

public SqlSession openSession(boolean autoCommit) {

return this.sqlSessionFactory.openSession(autoCommit);

}

显然是存在这样函数的,我们可以自己传参,来设置是否支持自动提交。

我的工具类可以改造为一个抽象类:

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 abstract class MyBatisUtil {

private static SqlSessionFactory sqlSessionFactory = null;

private static SqlSession sqlSession = null;

static {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的使用Mybatis Plus函数的示例: 假设我们有一个表名为user,包含以下字段:id、name、age、email。 1. 首先,在pom.xml文件中添加Mybatis Plus的依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>latest version</version> </dependency> ``` 2. 在Mapper接口中定义查询方法,例如根据年龄age查询: ``` import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper extends BaseMapper<User> { List<User> selectByAge(@Param("age") Integer age); } ``` 3. 在Service实现类中调用函数查询方法,例如查询年龄大于20的用户: ``` import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.util.List; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public List<User> getByAge(Integer age) { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.gt("age", age); // 使用Mybatis Plus的gt函数,查询年龄大于age的用户 List<User> userList = baseMapper.selectList(queryWrapper); return userList; } } ``` 这样就可以使用Mybatis Plus的函数查询数据了。除了gt函数,Mybatis Plus还提供了很多其他的函数,例如eq、ne、like、between等,具体可以参考官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值