如果上个问题的回答使用springboot项目的注解来写代码,请用java、
时间: 2024-02-27 19:51:30 浏览: 109
好的,以下是使用 Java 配置的方式来实现上一个问题的操作:
首先,我们需要在 application.properties 或 application.yml 中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
接着,我们需要定义实体类和 Mapper 接口:
Advert.java:
```java
public class Advert {
private Integer id;
private String name;
private Integer positionId;
private Integer mediaId;
private String link;
private Integer status;
private MediaFile mediaFile;
private AdPosition adPosition;
// 省略 getter 和 setter 方法
}
```
AdPosition.java:
```java
public class AdPosition {
private Integer id;
private String name;
// 省略 getter 和 setter 方法
}
```
MediaFile.java:
```java
public class MediaFile {
private Integer id;
private String name;
private Integer type;
private String url;
// 省略 getter 和 setter 方法
}
```
AdvertMapper.java:
```java
public interface AdvertMapper {
void insert(Advert advert);
}
```
接着,我们需要创建 Mapper 映射文件:
AdvertMapper.xml:
```xml
<?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.example.mapper.AdvertMapper">
<insert id="insert" parameterType="com.example.entity.Advert">
INSERT INTO `advert` (`name`, `position_id`, `media_id`, `link`, `status`)
VALUES (#{name}, #{positionId}, #{mediaId}, #{link}, #{status})
</insert>
</mapper>
```
最后,我们需要在 Spring Boot 中配置 Mybatis:
```java
@Configuration
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
} catch (IOException e) {
e.printStackTrace();
}
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
mapperScannerConfigurer.setBasePackage("com.example.mapper");
return mapperScannerConfigurer;
}
}
```
其中,SqlSessionFactoryBean 是用来配置 Mybatis 的,MapperScannerConfigurer 是用来扫描 Mapper 接口的。
最后,我们可以在 Service 层中使用 AdvertMapper 来插入数据:
```java
@Autowired
private AdvertMapper advertMapper;
public void addAdvert() {
Advert advert = new Advert();
advert.setName("广告名称");
advert.setPositionId(1);
advert.setMediaId(1);
advert.setLink("广告链接");
advert.setStatus(1);
advertMapper.insert(advert);
}
```
这样就完成了往 advert 表插入数据的操作。
阅读全文