使用Java编程和springboot框架实现创建活动并关联奖品,一个活动必须关联8个奖品,总概率为100% 给出相应的controller层,service层,service实现类,daoc层及mapper,
时间: 2024-03-15 14:45:16 浏览: 61
好的,以下是相应的代码实现:
1. Controller层
```java
@RestController
@RequestMapping("/activity")
public class ActivityController {
@Autowired
private ActivityService activityService;
@PostMapping("/create")
public ResponseEntity<Activity> createActivity(@RequestBody ActivityDTO activityDTO) {
Activity activity = activityService.createActivity(activityDTO);
return ResponseEntity.ok(activity);
}
}
```
2. Service层
```java
public interface ActivityService {
Activity createActivity(ActivityDTO activityDTO);
}
```
3. Service实现类
```java
@Service
public class ActivityServiceImpl implements ActivityService {
@Autowired
private ActivityMapper activityMapper;
@Override
public Activity createActivity(ActivityDTO activityDTO) {
// 验证奖品概率总和是否为100%
if (activityDTO.getPrizes().stream().mapToDouble(PrizeDTO::getProbability).sum() != 1.0) {
throw new IllegalArgumentException("奖品概率总和不为100%");
}
// 创建活动
Activity activity = new Activity();
activity.setName(activityDTO.getName());
activity.setStartTime(activityDTO.getStartTime());
activity.setEndTime(activityDTO.getEndTime());
// 创建奖品并关联活动
List<Prize> prizes = activityDTO.getPrizes().stream().map(prizeDTO -> {
Prize prize = new Prize();
prize.setName(prizeDTO.getName());
prize.setProbability(prizeDTO.getProbability());
prize.setActivity(activity);
return prize;
}).collect(Collectors.toList());
activity.setPrizes(prizes);
activityMapper.insert(activity);
return activity;
}
}
```
4. DAO层及Mapper
ActivityMapper.java
```java
@Mapper
public interface ActivityMapper {
void insert(Activity activity);
}
```
Activity.java
```java
public class Activity {
private Long id;
private String name;
private LocalDateTime startTime;
private LocalDateTime endTime;
private List<Prize> prizes;
// 省略getter和setter方法
}
```
Prize.java
```java
public class Prize {
private Long id;
private String name;
private double probability;
private Activity activity;
// 省略getter和setter方法
}
```
以上就是使用Java编程和Spring Boot框架实现创建活动并关联奖品的代码实现,希望能够对您有所帮助。
阅读全文