Development environment: IDEA 2022.1.4 Mybatis
When BiliBili learned SprintBoot before, I typed the code according to the video. SpringBoot integrates MyBatis and writes a separate mybatis-config.xml file. Configure data connection, mapper and other information. Later, I asked a colleague who is engaged in Java and told me that the mybatis-config.xml file can actually be written to application.yml. I didn't understand it at the time. Later, as I explored it, I gradually understood it.
I studied the video at that time and also wrote down a summary of the learning.
<?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核心配置文件--> <!--顺序 properties->settings->typeAliases->typeHandlers->objectFactory->objectWrapperFactory->reflectorFactory->plugins->environments->databaseIdProvider->mappers--> <configuration> <!--jdbc.properties配置文件--> <properties resource="jdbc.properties"></properties> <!--设置mybatis输出日志 Mybatis默认就是STDOUT_LOGGING--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!-- 类型别名 默认为类名 指定这个后 mapper的xml文件指定返回值时候 可直接写类名(不区分大小写) 建议直接拷贝类名 --> <typeAliases> <package name="com.ceaning.crudp.entity"/> </typeAliases> <!-- 环境配置 --> <!-- development IDEA默认 开发环境 --> <!-- 可以自定义 比如定义test formal 看心情 每个SqlSessionFactory实例只能选择一种环境 这个可随时配置 --> <!-- test 测试环境 --> <!-- formal 正式环境 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 映射器 每一个mapper.xml都需要在Mybatis的核心文件中注册! --> <!-- 注册方式1 使用xml文件 <mapper resource="com/ceaning/efmis/mapper/UserMapper.xml"/> --> <!-- 注册方式2 使用class文件 <mapper class="com.ceaning.efmis.mapper.UserMapper"/> --> <!-- 注册方式3 mapper代理方式 <package name="com.ceaning.efmis.mapper"/> --> <!-- 注册方式2(使用class文件)和注册方式3(使用包扫描注册) 1.接口和他的Mapper配置文件必须同名 2.接口和他的Mapper配置文件必须在同一个包下 --> <mappers> <package name="com.ceaning.crudp.mapper"/> </mappers> </configuration>
The content of jdbc.properties is as follows:
I write the jdbc configuration separately because I am worried that if it is deployed in WAR format in the future and the content of mybatis-config.xml is modified, there will be too much content and it is difficult to modify it. Wrong, just do a separate jdbc configuration. (Actually, I think too much)
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver url=jdbc:sqlserver://127.0.0.1:1433;databaseName=EFMIS username=sa password=123qwe,.
The function of the auxiliary class is to load the configuration and create a SqlSessionFactory when the class is initially called to facilitate subsequent SQL queries.
public class MybatisUtils { //SqlSessionFactory 静态单例模式 private static SqlSessionFactory sqlSessionFactory; //使用Mybatis第一步 获取SqlSessionFactory对象 static { try{ String resource="mybatis-config.xml"; InputStream inputStream= Resources.getResourceAsStream(resource); sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e){ e.printStackTrace(); } } //获取SqlSession实例 //该实例包含了面向数据库执行sql命令所需要的所有方法 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
Here I take the login operation as an example. This way you can connect to the database for operations.
@PostMapping("/user/login") public Result<?> login(@RequestBody User user){ SqlSession sqlSession= null; Map<String, Object> map= new HashMap<>(); try{ sqlSession= MybatisUtils.getSqlSession(); UserMapper mapper= sqlSession.getMapper(UserMapper.class); user= mapper.login(user); if (user!= null){ //生成token Map<String, String> tokenmap= new HashMap<>(); tokenmap.put("loginname", user.getLoginname()); tokenmap.put("password", user.getPassword()); String token= JwtUtils.getToken(tokenmap); //返回数据 map.put("user", user); map.put("token", token); return Result.ok(map); } else { return Result.error(CommonConstant.SYS_ERR_CODE, "用户不存在!"); } } catch (Exception e){ e.printStackTrace(); return Result.error("异常!"+ e.getMessage()); } finally { if (sqlSession!= null){ sqlSession.close(); } } }
Don’t worry about the extra content. The main thing is to configure the data source spring.datasource. Configure database connection information.
Server: port: 8090 spring: # quartz定时任务配置 quartz: # 数据库存储方式 job-store-type: jdbc org: quartz: jobStore: class: org.springframework.scheduling.quartz.LocalDataSourceJobStore #配置数据源 datasource: url: jdbc:sqlserver://127.0.0.1:1433;SelectMethod=cursor;databaseName=EFMIS username: sa password: 123qwe,. driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver #json jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 #热部署 devtools: restart: enabled: true additional-paths: src/main/java exclude: static/** jta: atomikos: properties: recovery: forget-orphaned-log-entries-delay: mybatis: configuration: #开启驼峰映射 map-underscore-to-camel-case: true #开启缓存 cache-enabled: true #加载mapper.xml文件 mapper-locations: classpath:com/ceaning/crudp/mapper/*.xml #别名扫描 type-aliases-package: com.ceaning.crudp.entity logging: config: classpath:logback-spring.xml
@Component public class SpringUtils implements BeanFactoryPostProcessor { /** * Spring应用上下文环境 */ private static ConfigurableListableBeanFactory beanFactory; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { SpringUtils.beanFactory= configurableListableBeanFactory; } public static <T> T getBean(String name) throws BeansException{ name= lowerCaseInit(name); if(containsBean(name)){ return (T) beanFactory.getBean(name); } else{ return null; } } /** * 获取 * @param cls * @return * @param <T> * @throws BeansException */ public static <T> T getBean(Class<T> cls) throws BeansException{ T result= (T) beanFactory.getBean(cls); return result; } /** * 判断 BeanFactory是否包含bean对象 * @param name * @return */ public static boolean containsBean(String name){ return beanFactory.containsBean(name); } /** * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) * @param name * @return * @throws NoSuchBeanDefinitionException */ public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException{ return beanFactory.isSingleton(name); } public static Class<?> getType(String name) throws NoSuchBeanDefinitionException{ return beanFactory.getType(name); } public static String[] getAliases(String name) throws NoSuchBeanDefinitionException{ return beanFactory.getAliases(name); } /** * 首字母小写 * @param name * @return */ private static String lowerCaseInit(String name){ if(name.length()>0){ char c= name.charAt(0); if(c>=65 && c<=90){ int i= c+ 32; return ((char)i)+ name.substring(1); } else{ return name; } } else{ return null; } } }
Here we take the login operation as an example. Database connection operations can also be performed.
@PostMapping("/user/login") public Result<?> login(@RequestBody User user){ Map<String, Object> map= new HashMap<>(); try{ UserMapper mapper= SpringUtils.getBean(UserMapper.class); user= mapper.login(user); if (user!= null){ //生成token Map<String, String> tokenmap= new HashMap<>(); tokenmap.put("loginname", user.getLoginname()); tokenmap.put("password", user.getPassword()); String token= JwtUtils.getToken(tokenmap); //返回数据 map.put("user", user); map.put("token", token); return Result.ok(map); } else { return Result.error(CommonConstant.SYS_ERR_CODE, "用户不存在!"); } } catch (Exception e){ e.printStackTrace(); return Result.error("异常!"+ e.getMessage()); } }
The above is the detailed content of How to configure SpringBoot Mybatis files. For more information, please follow other related articles on the PHP Chinese website!