时间:2021-07-01 10:21:17 帮助过:13人阅读
<?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> <environments default="development"> <environment id="development"> <!-- 配置JDBC事务,此事务由mybatis管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置连接池,此连接池为mybatis连接池 --> <dataSource type="POOLED"> <property name="driver" value="org.sqlite.JDBC"/> <property name="url" value="jdbc:sqlite:../webservice-boot/src/main/resources/DB.sqlite3"/> <property name="username" value=""/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis/mapper/AdminMapper.xml" /> </mappers> </configuration>View Code
AdminDO.java
package com.pxinhai.webservice.dal.admin; public class AdminDO { private String adminID; public String getAdminID() { return adminID; } public void setAdminID(String adminID) { this.adminID = adminID; } }View Code
DalFactory.java 数据管理工厂层,从mybatis-config里获取数据配置文件,创建sqlsession
String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory.openSession();View Code
AdminMapper.xml 对sql语句与DO的映射配置,需要注意namespace与dal接口层要一致
<?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="com.pxinhai.webservice.dal.admin.AdminDal" > <select id="findAdminById" parameterType="String" resultType="com.pxinhai.webservice.dal.admin.AdminDO"> SELECT * FROM admin WHERE adminID =#{adminID} </select> </mapper>View Code
AdminDal.java 接口层 ,spring规范打 Repository注解注入到容器里去就不需要在mybatis-config指定了
package com.pxinhai.webservice.dal.admin; import org.springframework.stereotype.Repository; @Repository public interface AdminDal { AdminDO findAdminById(String adminID); }View Code
单元测试
@SpringBootConfiguration @RunWith(SpringRunner.class) @SpringBootTest public class AdminDalTest { @Test public void testFindAdminById(){ SqlSession sqlSession=new DalFactory().getSession(); AdminDal dal=sqlSession.getMapper(AdminDal.class); AdminDO mm=dal.findAdminById("admin"); Assert.assertNotNull(mm); sqlSession.close(); } }View Code
如果通过SpringApplication.rum 来启运项目,还需手运排除自动加载数据库配置文件。
在应用启动如入的class文件加:@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
spring boot +mybatis 操作sqlite数据库
标签:isp package data tac open null encoding port 解决