redisTemplate.opsForHash().entries("stars");通过service,controller,dao层写入MySQL
时间: 2023-05-24 07:06:51 浏览: 205
1. 在Service层中获取Redis中的数据,并进行存储到MySQL中的操作。
```java
@Service
public class StarService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StarDao starDao;
public void saveStarsToMysql() {
Map<Object, Object> stars = redisTemplate.opsForHash().entries("stars");
for (Map.Entry<Object, Object> entry : stars.entrySet()) {
Star star = new Star();
star.setId((Long) entry.getKey());
star.setName((String) entry.getValue());
starDao.save(star);
}
}
}
```
2. 在controller层中调用Service层的方法进行数据存储。
```java
@RestController
@RequestMapping("/stars")
public class StarController {
@Autowired
private StarService starService;
@PostMapping("/savestars")
public String saveStarsToMysql(){
starService.saveStarsToMysql();
return "stars saved successfully!";
}
}
```
3. 在Dao层中实现数据存储的操作。
```java
@Repository
public interface StarDao extends JpaRepository<Star, Long> {
}
```
```java
@Entity
@Table(name = "stars")
public class Star {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
阅读全文