dao层和mapper中的xml关联
时间: 2023-04-23 16:01:56 浏览: 104
在Java中的DAO(数据访问对象)层中,通常使用MyBatis等ORM(对象关系映射)框架来管理与数据库的交互。其中,DAO层中的Mapper接口用于定义数据访问方法,而Mapper.xml文件则用于存储SQL语句的实现。
在Mapper.xml文件中,需要定义SQL语句的ID、参数、返回类型等信息,并实现SQL语句的具体逻辑。而在Mapper接口中,需要定义与Mapper.xml文件中相应SQL语句ID对应的方法,并指定对应的输入参数和返回类型。这样,在程序中调用Mapper接口的方法时,框架会自动查找与该方法ID相应的Mapper.xml文件中的SQL语句,并将参数传递给该SQL语句进行执行,最终返回结果。
因此,通过在Mapper.xml文件中定义SQL语句,并在Mapper接口中定义对应的方法,就可以实现DAO层与数据库的交互。
相关问题
使用Java编程和springboot框架,使用Spring MVC框架,连接mysql数据库实现 1.创建活动并关联奖品,一个活动必须关联8个奖品,总概率为100% 2.修改活动 活动名称不能重复 并更新关联奖品,给出具体程序,包括给出相应的controller层,service层,service实现类,dao层及mapper.xml文件
好的,针对您的问题,我会给出一个简单的示例程序,供您参考。需要说明的是,这只是一个示例程序,实际情况中还需要根据具体业务需求进行修改和完善。
首先,我们需要创建一个活动实体类,代码如下:
```java
public class Activity {
private String id;
private String name;
private List<Prize> prizes;
// getter and setter methods
}
```
其中,id为活动id,name为活动名称,prizes为关联的奖品列表。接着,我们需要创建一个奖品实体类,代码如下:
```java
public class Prize {
private String id;
private String name;
private int probability;
// getter and setter methods
}
```
其中,id为奖品id,name为奖品名称,probability为奖品概率。
接下来,我们需要创建对应的DAO层和Mapper.xml文件,用于实现对数据库的操作。这里我们使用Mybatis框架进行操作。DAO层代码如下:
```java
@Repository
public class ActivityDao {
@Autowired
private SqlSession sqlSession;
public void createActivity(Activity activity) {
sqlSession.insert("ActivityMapper.createActivity", activity);
}
public void updateActivity(Activity activity) {
sqlSession.update("ActivityMapper.updateActivity", activity);
}
public Activity getActivityById(String id) {
return sqlSession.selectOne("ActivityMapper.getActivityById", id);
}
public Activity getActivityByName(String name) {
return sqlSession.selectOne("ActivityMapper.getActivityByName", name);
}
}
```
其中,createActivity方法用于创建活动,updateActivity方法用于更新活动信息,getActivityById方法用于根据id获取活动信息,getActivityByName方法用于根据名称获取活动信息。注意,这里使用了@Autowired注解,需要在Spring配置文件中进行配置。
接下来,我们需要创建对应的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="ActivityMapper">
<insert id="createActivity" parameterType="Activity">
insert into activity(id, name)
values(#{id}, #{name})
</insert>
<update id="updateActivity" parameterType="Activity">
update activity
set name = #{name}
where id = #{id}
</update>
<select id="getActivityById" parameterType="String" resultMap="activityResultMap">
select *
from activity
where id = #{id}
</select>
<select id="getActivityByName" parameterType="String" resultMap="activityResultMap">
select *
from activity
where name = #{name}
</select>
<resultMap id="activityResultMap" type="Activity">
<id column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
</mapper>
```
其中,createActivity对应创建活动操作,updateActivity对应更新活动操作,getActivityById对应根据id获取活动信息操作,getActivityByName对应根据名称获取活动信息操作。
接下来,我们需要创建对应的Service层和实现类。Service层代码如下:
```java
public interface ActivityService {
void createActivity(Activity activity);
void updateActivity(Activity activity);
Activity getActivityById(String id);
Activity getActivityByName(String name);
}
@Service
public class ActivityServiceImpl implements ActivityService {
@Autowired
private ActivityDao activityDao;
@Override
public void createActivity(Activity activity) {
// 校验活动名称是否重复
Activity oldActivity = activityDao.getActivityByName(activity.getName());
if (oldActivity != null) {
throw new RuntimeException("活动名称已存在");
}
// 校验关联奖品数量是否正确
List<Prize> prizes = activity.getPrizes();
if (prizes == null || prizes.size() != 8) {
throw new RuntimeException("奖品数量不正确");
}
// 校验奖品概率之和是否为100%
int totalProbability = 0;
for (Prize prize : prizes) {
totalProbability += prize.getProbability();
}
if (totalProbability != 100) {
throw new RuntimeException("奖品概率之和不为100%");
}
// 保存活动信息
activityDao.createActivity(activity);
}
@Override
public void updateActivity(Activity activity) {
// 校验活动名称是否重复
Activity oldActivity = activityDao.getActivityByName(activity.getName());
if (oldActivity != null && !oldActivity.getId().equals(activity.getId())) {
throw new RuntimeException("活动名称已存在");
}
// 校验关联奖品数量是否正确
List<Prize> prizes = activity.getPrizes();
if (prizes == null || prizes.size() != 8) {
throw new RuntimeException("奖品数量不正确");
}
// 校验奖品概率之和是否为100%
int totalProbability = 0;
for (Prize prize : prizes) {
totalProbability += prize.getProbability();
}
if (totalProbability != 100) {
throw new RuntimeException("奖品概率之和不为100%");
}
// 更新活动信息
activityDao.updateActivity(activity);
}
@Override
public Activity getActivityById(String id) {
return activityDao.getActivityById(id);
}
@Override
public Activity getActivityByName(String name) {
return activityDao.getActivityByName(name);
}
}
```
其中,createActivity方法用于创建活动,updateActivity方法用于更新活动信息,getActivityById方法用于根据id获取活动信息,getActivityByName方法用于根据名称获取活动信息。注意,这里使用了@Autowired注解,需要在Spring配置文件中进行配置。
最后,我们需要创建对应的Controller层,代码如下:
```java
@RestController
@RequestMapping("/activity")
public class ActivityController {
@Autowired
private ActivityService activityService;
@PostMapping("/create")
public void createActivity(@RequestBody Activity activity) {
activityService.createActivity(activity);
}
@PostMapping("/update")
public void updateActivity(@RequestBody Activity activity) {
activityService.updateActivity(activity);
}
@GetMapping("/{id}")
public Activity getActivityById(@PathVariable String id) {
return activityService.getActivityById(id);
}
@GetMapping("/name/{name}")
public Activity getActivityByName(@PathVariable String name) {
return activityService.getActivityByName(name);
}
}
```
其中,createActivity对应创建活动操作,updateActivity对应更新活动操作,getActivityById对应根据id获取活动信息操作,getActivityByName对应根据名称获取活动信息操作。
至此,我们完成了使用Java编程和SpringBoot框架,使用SpringMVC框架,连接MySQL数据库实现创建活动并关联奖品,一个活动必须关联8个奖品,总概率为100%以及修改活动操作的示例程序。
使用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
阅读全文