java-mybatis注解开发、整合Spring、JUnit4
1、依赖
<!-- Spring容器 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- mybatis与spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
2、数据库配置信息
3、配置文件 mybatisConfig.xml
<?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 resource="druid.properties"/>
<typeAliases>
<package name="cn.tjhis.domain"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.tjhis.mapper"/>
</mappers>
</configuration>
4、实体
5、mapper
public interface ProductInfoMapper {
/**
* 新增
* @param p 商品信息
* @return 成功或者失败
*/
@Insert("insert into product_info(item_Name,item_Code,item_Spec,item_Status,create_Date)values(#{itemName},#{itemCode},#{itemSpec},#{itemStatus},#{createDate})")
boolean insert(ProductInfo p);
/**
* 更新商品
* @param p 商品信息
* @return 成功或者失败
*/
@Update("update product_info set item_Name=#{itemName},item_Code=#{itemCode},item_Spec=#{itemSpec},item_Status=#{itemStatus},create_Date=#{createDate} where id = #{id}")
boolean update(ProductInfo p);
/**
* 根据ID删除商品
* @param id ID
* @return 成功或者失败
*/
@Delete("delete from product_info where id = #{id}")
boolean delete(int id);
/**
* 根据id查找商品
* @param id ID
* @return 商品信息
*/
@Select("select * from product_info where id=#{id}")
@Results({
@Result(column = "item_Name", property = "itemName"),
@Result(column = "item_Code", property = "itemCode"),
@Result(column = "item_Spec", property = "itemSpec"),
@Result(column = "item_Status", property = "itemStatus"),
@Result(column = "create_Date", property = "createDate"),
})
ProductInfo getProductInfoById(int id);
/**
* 获取所有的商品信息
* @return 商品信息
*/
@Select("select * from product_info")
@Results({
@Result(column = "item_Name", property = "itemName"),
@Result(column = "item_Code", property = "itemCode"),
@Result(column = "item_Spec", property = "itemSpec"),
@Result(column = "item_Status", property = "itemStatus"),
@Result(column = "create_Date", property = "createDate"),
})
List<ProductInfo> getProductInfo();
}
6、测试
public class Main {
public static void main(String[] args) throws IOException {
// 获取配置文件
InputStream resource = Resources.getResourceAsStream("mybatisConfig.xml");
// 获取session工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);
// 获取session
try (SqlSession session = factory.openSession()) {
ProductInfoMapper mapper = session.getMapper(ProductInfoMapper.class);
// 查询
// ProductInfo info = mapper.getProductInfoById(1);
// info.setCreateDate(LocalDateTime.of(2022,10,1,10,22,22));
// 更新
// boolean update = mapper.update(info);
// 新增
/*
ProductInfo info = new ProductInfo();
info.setCreateDate(LocalDateTime.now());
info.setItemCode("H002000202");
info.setItemSpec("10g*1盒北京大兴");
info.setItemName("太太口服液");
info.setItemStatus(0);
*/
// 删除
boolean delete = mapper.delete(3);
System.out.println(delete);
}
System.out.println("Hello world!");
}
}
6、整合Spring
- 添加依赖
mybatis-spring
和spring-jdbc
两个依赖 - 增加配置对象
@Configuration
@ComponentScan("cn.tjhis")
@PropertySource({"classpath:druid.properties"})
@Import({DbConfig.class,MybatisConfig.class})
public class SpringConfig {
}
public class DbConfig {
@Value("${jdbc.driver-class-name}")
private String className;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.maxActive}")
private int maxActive;
@Value("${jdbc.minIdle}")
private int minIdle;
@Value("${jdbc.maxWait}")
private int maxWait;
@Value("${jdbc.initialSize}")
private int initialSize;
@Bean
public DataSource dataSource() {
System.out.println(className);
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(className);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minIdle);
dataSource.setMaxWait(maxWait);
dataSource.setInitialSize(initialSize);
return dataSource;
}
}
// 下面这个是为了替代配置文件 mybatisConfig.xml,有了他,可以删除mybatisConfig.xml文件了
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
// 相当于配置文件的<typeAliases>标签
sfb.setTypeAliasesPackage("cn.tjhis.domain");
// 设置数据源
sfb.setDataSource(dataSource);
return sfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
// 替代配置文件的mapper标签
msc.setBasePackage("cn.tjhis.mapper");
return msc;
}
}
- service层
public interface ProductInfoService {
/**
* 新增
* @param p 商品信息
* @return 成功或者失败
*/
boolean insert(ProductInfo p);
/**
* 更新商品
* @param p 商品信息
* @return 成功或者失败
*/
boolean update(ProductInfo p);
/**
* 根据ID删除商品
* @param id ID
* @return 成功或者失败
*/
boolean delete(int id);
/**
* 根据id查找商品
* @param id ID
* @return 商品信息
*/
ProductInfo getProductInfoById(int id);
/**
* 获取所有的商品信息
* @return 商品信息
*/
List<ProductInfo> getProductInfo();
}
- 测试
public class Main2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
ProductInfoService service = context.getBean(ProductInfoService.class);
List<ProductInfo> infos = service.getProductInfo();
System.out.println(infos);
}
}
7、整合junit
- 导入依赖
<!-- 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
</dependency>
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class MySpringTest {
@Autowired
private ProductInfoService service;
@Test
public void testSelect(){
ProductInfo info = service.getProductInfoById(2);
System.out.println(info);
}
}
世界上没有什么事情是跑步解决不了的,如果有,那就再跑一会!