创建A表,id分别为1,2,3,name分别为a,b,c,MySQL代码实现
时间: 2024-06-01 12:14:14 浏览: 41
可以使用如下的MySQL代码实现:
CREATE TABLE A (
id INT(11) NOT NULL,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO A (id, name) VALUES (1, 'a'), (2, 'b'), (3, 'c');
说明:以上代码创建了一个名为A的表,包含id和name两个字段,其中id作为主键。然后插入了三条数据,分别为id为1、name为a,id为2、name为b和id为3、name为c。
相关问题
使用Java编程和springboot框架,连接mysql数据库(所需的三个表分别为奖品表名为a,活动表名为b,两者关联的表为c(中奖概率字段位于c表))实现下面两个功能 :1.创建活动并关联奖品,一个活动必须关联8个奖品,总概率为100% 2.修改活动 活动名称不能重复 并更新关联奖品。给出具体程序,包括给出相应的controller层,service层,service实现类,dao层及mapper.xml文件
好的,以下是Java编写的代码示例,包括controller、service、dao和mapper.xml文件。
Controller层:
```java
@RestController
@RequestMapping("/activity")
public class ActivityController {
@Autowired
private ActivityService activityService;
@PostMapping("/create")
public ResponseEntity createActivity(@RequestBody ActivityDto activityDto) {
activityService.createActivity(activityDto);
return ResponseEntity.ok("Create activity success");
}
@PutMapping("/update")
public ResponseEntity updateActivity(@RequestBody ActivityDto activityDto) {
activityService.updateActivity(activityDto);
return ResponseEntity.ok("Update activity success");
}
}
```
Service层:
```java
public interface ActivityService {
void createActivity(ActivityDto activityDto);
void updateActivity(ActivityDto activityDto);
}
```
Service实现类:
```java
@Service
public class ActivityServiceImpl implements ActivityService {
@Autowired
private ActivityMapper activityMapper;
@Autowired
private PrizeMapper prizeMapper;
@Autowired
private ActivityPrizeMapper activityPrizeMapper;
@Override
public void createActivity(ActivityDto activityDto) {
// 1. 创建活动
Activity activity = new Activity();
activity.setName(activityDto.getName());
activityMapper.insert(activity);
// 2. 关联奖品
List<PrizeDto> prizeDtos = activityDto.getPrizes();
List<ActivityPrize> activityPrizes = new ArrayList<>();
double totalProbability = 0;
for (PrizeDto prizeDto : prizeDtos) {
ActivityPrize activityPrize = new ActivityPrize();
activityPrize.setActivityId(activity.getId());
activityPrize.setPrizeId(prizeDto.getId());
activityPrize.setProbability(prizeDto.getProbability());
activityPrizes.add(activityPrize);
totalProbability += prizeDto.getProbability();
}
// 3. 校验概率是否为100%
if (totalProbability != 100) {
throw new RuntimeException("Total probability must be 100%");
}
// 4. 保存关联关系
activityPrizeMapper.batchInsert(activityPrizes);
}
@Override
public void updateActivity(ActivityDto activityDto) {
// 1. 查询活动
Activity activity = activityMapper.selectByPrimaryKey(activityDto.getId());
if (activity == null) {
throw new RuntimeException("Activity not exists");
}
// 2. 更新活动名称
if (!activity.getName().equals(activityDto.getName())) {
Activity activityByName = activityMapper.selectByName(activityDto.getName());
if (activityByName != null) {
throw new RuntimeException("Activity name already exists");
}
activity.setName(activityDto.getName());
activityMapper.updateByPrimaryKey(activity);
}
// 3. 更新关联奖品
List<PrizeDto> prizeDtos = activityDto.getPrizes();
List<ActivityPrize> activityPrizes = new ArrayList<>();
double totalProbability = 0;
for (PrizeDto prizeDto : prizeDtos) {
ActivityPrize activityPrize = new ActivityPrize();
activityPrize.setActivityId(activity.getId());
activityPrize.setPrizeId(prizeDto.getId());
activityPrize.setProbability(prizeDto.getProbability());
activityPrizes.add(activityPrize);
totalProbability += prizeDto.getProbability();
}
// 4. 校验概率是否为100%
if (totalProbability != 100) {
throw new RuntimeException("Total probability must be 100%");
}
// 5. 删除旧的关联关系,保存新的关联关系
activityPrizeMapper.deleteByActivityId(activity.getId());
activityPrizeMapper.batchInsert(activityPrizes);
}
}
```
DAO层:
```java
@Repository
public interface ActivityMapper extends BaseMapper<Activity> {
Activity selectByName(String name);
}
```
```java
@Repository
public interface PrizeMapper extends BaseMapper<Prize> {
}
```
```java
@Repository
public interface ActivityPrizeMapper extends BaseMapper<ActivityPrize> {
void deleteByActivityId(Integer activityId);
void batchInsert(List<ActivityPrize> activityPrizes);
}
```
Mapper.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.ActivityMapper">
<resultMap id="BaseResultMap" type="com.example.entity.Activity">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select id, name
from activity
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select id, name
from activity
where name = #{name,jdbcType=VARCHAR}
</select>
<insert id="insert" parameterType="com.example.entity.Activity">
insert into activity (name)
values (#{name,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.example.entity.Activity">
update activity
set name = #{name,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
```
```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.PrizeMapper">
<resultMap id="BaseResultMap" type="com.example.entity.Prize">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select id, name
from prize
where id = #{id,jdbcType=INTEGER}
</select>
</mapper>
```
```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.ActivityPrizeMapper">
<resultMap id="BaseResultMap" type="com.example.entity.ActivityPrize">
<result column="activity_id" jdbcType="INTEGER" property="activityId" />
<result column="prize_id" jdbcType="INTEGER" property="prizeId" />
<result column="probability" jdbcType="DOUBLE" property="probability" />
</resultMap>
<delete id="deleteByActivityId" parameterType="java.lang.Integer">
delete from activity_prize
where activity_id = #{activityId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.example.entity.ActivityPrize">
insert into activity_prize (activity_id, prize_id, probability)
values (#{activityId,jdbcType=INTEGER}, #{prizeId,jdbcType=INTEGER}, #{probability,jdbcType=DOUBLE})
</insert>
<insert id="batchInsert">
<foreach collection="list" item="item" index="index" separator=";">
insert into activity_prize (activity_id, prize_id, probability)
values (#{item.activityId,jdbcType=INTEGER}, #{item.prizeId,jdbcType=INTEGER}, #{item.probability,jdbcType=DOUBLE})
</foreach>
</insert>
</mapper>
```
以上是Java编写的实现,使用了SpringBoot和MyBatis框架,其中controller层提供了两个接口,分别用于创建和更新活动,service层提供了对应的接口实现,dao层提供了数据库操作的接口,mapper.xml文件提供了对应的SQL语句。
使用Java编程和springboot框架,连接mysql数据库(奖品表名为a,活动表名为b,两者关联的表为c)实现 1.创建活动并关联奖品,一个活动必须关联8个奖品,总概率为100% 2.修改活动 活动名称不能重复 并更新关联奖品,给出具体程序,包括给出相应的controller层,service层,service实现类,dao层及mapper.xml文件
好的,首先需要创建一个Spring Boot项目,并且添加相关依赖,包括 Spring Boot、MyBatis、MySQL Connector 等。
接下来,我们需要在 MySQL 中创建两个表,分别为 a 和 b,以及一个关联表 c。表结构如下:
```
-- 奖品表 a
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`probability` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- 活动表 b
CREATE TABLE `b` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
-- 关联表 c
CREATE TABLE `c` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aid` int(11) NOT NULL,
`bid` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_aid_bid` (`aid`,`bid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
```
然后,我们需要定义实体类 Prize 和 Activity,以及它们的关联类 PrizeActivity。
```
// Prize.java
public class Prize {
private Integer id;
private String name;
private Integer probability;
// 省略 getter 和 setter
}
// Activity.java
public class Activity {
private Integer id;
private String name;
private List<Prize> prizes;
// 省略 getter 和 setter
}
// PrizeActivity.java
public class PrizeActivity {
private Integer id;
private Integer aid;
private Integer bid;
// 省略 getter 和 setter
}
```
在 DAO 层中,我们需要定义三个接口:PrizeMapper、ActivityMapper 和 PrizeActivityMapper。
```
// PrizeMapper.java
@Mapper
public interface PrizeMapper {
@Select("SELECT * FROM a")
List<Prize> getAllPrizes();
}
// ActivityMapper.java
@Mapper
public interface ActivityMapper {
@Select("SELECT * FROM b WHERE id = #{id}")
Activity getActivityById(Integer id);
@Select("SELECT * FROM b WHERE name = #{name}")
Activity getActivityByName(String name);
@Insert("INSERT INTO b (name) VALUES (#{name})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int createActivity(Activity activity);
@Update("UPDATE b SET name = #{name} WHERE id = #{id}")
void updateActivity(Activity activity);
}
// PrizeActivityMapper.java
@Mapper
public interface PrizeActivityMapper {
@Insert("INSERT INTO c (aid, bid) VALUES (#{aid}, #{bid})")
void createPrizeActivity(PrizeActivity prizeActivity);
@Delete("DELETE FROM c WHERE bid = #{bid}")
void deletePrizeActivityByActivityId(Integer bid);
}
```
接下来,我们需要在 Service 层中定义三个接口:PrizeService、ActivityService 和 PrizeActivityService,并且实现它们的方法。
```
// PrizeService.java
public interface PrizeService {
List<Prize> getAllPrizes();
}
// ActivityService.java
public interface ActivityService {
Activity getActivityById(Integer id);
Activity getActivityByName(String name);
Activity createActivity(Activity activity);
void updateActivity(Activity activity);
}
// PrizeActivityService.java
public interface PrizeActivityService {
void createPrizeActivity(Integer aid, Integer bid);
void deletePrizeActivityByActivityId(Integer bid);
}
```
```
// PrizeServiceImpl.java
@Service
public class PrizeServiceImpl implements PrizeService {
private final PrizeMapper prizeMapper;
public PrizeServiceImpl(PrizeMapper prizeMapper) {
this.prizeMapper = prizeMapper;
}
@Override
public List<Prize> getAllPrizes() {
return prizeMapper.getAllPrizes();
}
}
// ActivityServiceImpl.java
@Service
public class ActivityServiceImpl implements ActivityService {
private final ActivityMapper activityMapper;
private final PrizeActivityService prizeActivityService;
public ActivityServiceImpl(ActivityMapper activityMapper, PrizeActivityService prizeActivityService) {
this.activityMapper = activityMapper;
this.prizeActivityService = prizeActivityService;
}
@Override
public Activity getActivityById(Integer id) {
return activityMapper.getActivityById(id);
}
@Override
public Activity getActivityByName(String name) {
return activityMapper.getActivityByName(name);
}
@Override
public Activity createActivity(Activity activity) {
activityMapper.createActivity(activity);
for (Prize prize : activity.getPrizes()) {
prizeActivityService.createPrizeActivity(prize.getId(), activity.getId());
}
return activity;
}
@Override
public void updateActivity(Activity activity) {
activityMapper.updateActivity(activity);
prizeActivityService.deletePrizeActivityByActivityId(activity.getId());
for (Prize prize : activity.getPrizes()) {
prizeActivityService.createPrizeActivity(prize.getId(), activity.getId());
}
}
}
// PrizeActivityServiceImpl.java
@Service
public class PrizeActivityServiceImpl implements PrizeActivityService {
private final PrizeActivityMapper prizeActivityMapper;
public PrizeActivityServiceImpl(PrizeActivityMapper prizeActivityMapper) {
this.prizeActivityMapper = prizeActivityMapper;
}
@Override
public void createPrizeActivity(Integer aid, Integer bid) {
PrizeActivity prizeActivity = new PrizeActivity();
prizeActivity.setAid(aid);
prizeActivity.setBid(bid);
prizeActivityMapper.createPrizeActivity(prizeActivity);
}
@Override
public void deletePrizeActivityByActivityId(Integer bid) {
prizeActivityMapper.deletePrizeActivityByActivityId(bid);
}
}
```
最后,在 Controller 层中定义 ActivityController,并且注入 ActivityService。
```
@RestController
@RequestMapping("/activity")
public class ActivityController {
private final ActivityService activityService;
public ActivityController(ActivityService activityService) {
this.activityService = activityService;
}
@GetMapping("/{id}")
public Activity getActivityById(@PathVariable("id") Integer id) {
return activityService.getActivityById(id);
}
@GetMapping("/name/{name}")
public Activity getActivityByName(@PathVariable("name") String name) {
return activityService.getActivityByName(name);
}
@PostMapping("")
public Activity createActivity(@RequestBody Activity activity) {
return activityService.createActivity(activity);
}
@PutMapping("/{id}")
public void updateActivity(@PathVariable("id") Integer id, @RequestBody Activity activity) {
if (!id.equals(activity.getId())) {
throw new IllegalArgumentException("The id is not matched.");
}
activityService.updateActivity(activity);
}
}
```
好了,以上就是实现的全部内容。如果需要更详细的代码实现可以参考:https://github.com/shadowice0904/spring-boot-mybatis-example
阅读全文