定制鞋子哪个网站好app开发自学教程
使用Mybatis当前最火的插件:MybatisX。
在IDEA中安装MyBatisX
插件。
该插件主要功能如下:
-
生成mapper xml文件
-
快速从代码跳转到mapper及从mapper返回代码
-
mybatis自动补全及语法错误提示
-
集成mybatis Generate GUI界面
-
根据数据库注解,生成swagger model注解
一、使用步骤
1.1 IDEA连接数据库
1.2 选择数据表
选一或多张表,右键选择MybatisX-Generator
1.3 配置生成方式
GUI第一页,用于设置实体类的创建配置,需要设置信息如图。
GUI第二页,用于设置映射文件,需要设置的信息如图。
生成的文件结构如下:
二、编写代码测试
2.1 编写功能代码
BlogMapper.java接口文件:
public interface BlogMapper {// 根据博文id查询博文信息Blog getBlogByAid(Integer aid);}
BlogMapper.xml文件:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.pxy.dao.BlogMapper"><sql id="Base_Column_List">bid,title,content,aid,createtime,type</sql><!-- 根据主键查询博文 --><select id="getBlogByAid" parameterType="java.lang.Integer" resultType="com.pxy.po.Blog">select<include refid="Base_Column_List" />from blogtblwhere bid = #{bid}</select></mapper>
2.2 添加映射文件引用
在配置文件中引用BlogMapper.xml:
<mappers><mapper resource="com/pxy/dao/AuthorMapper.xml"></mapper><mapper resource="com/pxy/dao/BlogMapper.xml"></mapper></mappers>
2.3 编写测试类
在test包中创建BlogTest类
public class BlogTest {@Testpublic void testGetAuthor() {SqlSession sqlSession = Utils.getSqlSession();BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);Blog blog = blogMapper.getBlogByAid(1);System.out.println(blog);sqlSession.close();}}
创建SQLSession对象的方法封装在Utils类中:
public class Utils {public static SqlSession getSqlSession(){SqlSession sqlSession = null;try{//读取配置文件,获得配置文件信息InputStream input = Resources.getResourceAsStream("SqlMapConfig.xml");//通过配置信息创建SqlSessionFactorySqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(input);//通过SqlSessionFactory打开数据库会话sqlSession = ssf.openSession();} catch (Exception e) {e.printStackTrace();}return sqlSession;}}
运行结果如下:
搞定,收功!