前言
学习了Java的相关方面知识之后,但对于各层次之间的关系以及部署,可能还会有些陌生感,下面以代码讲解各层之间的关系。
(企业中多数以Springboot为例,下面的代码都是以Springboot为例)
1. Demo1
简单的Spring Boot项目的基本结构,其中包含了实体类、Mapper接口和XML文件、Service接口和实现类以及Controller。
根据实际需求进行适当的调整和扩展。在实际项目中,还需要配置数据库连接、事务管理等相关内容
一、定义实体类(Entity):
// User.java
public class User {
private Long id;
private String username;
private String email;
// Getters and setters
}
二、创建Mapper接口:
// UserMapper.java
import java.util.List;
public interface UserMapper {
List<User> getAllUsers();
User getUserById(Long id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
三、创建Mapper XML文件:(在resources目录下创建一个与Mapper接口同名的XML文件,定义SQL语句):
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="getAllUsers" resultType="com.example.model.User">
SELECT * FROM users;
</select>
<select id="getUserById" parameterType="Long" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id};
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO users (username, email) VALUES (#{username}, #{email});
</insert>
<update id="updateUser" parameterType="com.example.model.User">
UPDATE users SET username = #{username}, email = #{email} WHERE id = #{id};
</update>
<delete id="deleteUser" parameterType="Long">
DELETE FROM users WHERE id = #{id};
</delete>
</mapper>
四、创建Service接口和实现类:(实现类记得写@Service):
// UserService.java
public interface UserService {
List<User> getAllUsers();
User getUserById(Long id);
void saveUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
// UserServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
@Autowired
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
@Override
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
@Override
public void saveUser(User user) {
userMapper.insertUser(user);
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public void deleteUser(Long id) {
userMapper.deleteUser(id);
}
}
五、创建Controller:(用于处理HTTP请求):
// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping
public void saveUser(@RequestBody User user) {
userService.saveUser(user);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
2. Demo2
上述改进方案可以摘Service中继承Iservice,使用继承类中的方法:
一、 修改UserService接口:在com.example.service包下创建一个UserService接口,继承IService:
// UserService.java
import com.example.model.User;
import com.baomidou.mybatisplus.extension.service.IService;
public interface UserService extends IService<User> {
// 这里可以添加自定义的业务方法
}
二、创建UserServiceImpl实现类:(ServiceImpl已经实现了IService中的基本方法,在此基础上添加自定义的业务方法)
// UserServiceImpl.java
import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
// 这里可以添加自定义的业务方法的实现
}
三、使用UserService:在Controller中注入UserService,即可使用自动生成的方法
// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.model.User;
import com.example.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.list();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getById(id);
}
@PostMapping
public void saveUser(@RequestBody User user) {
userService.save(user);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userService.updateById(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.removeById(id);
}
}
3. Demo3
对于MybatisPlus中,其实更多的是Mapper来操作,上述Service的操作,最后都会通过Mapepr来操作
可以看这篇文章的示例讲解:快速理解Mybatis-plus中BaseMapper、IService和ServiceImpl
类似如下:
@Test
public void getUserById() {
List<User> one = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getUsername,"manong"));
System.out.println(one);
}
4. Mybatis自动生成
使用Spring Boot和MyBatis的整合框架,可以借助MyBatis Generator自动生成实体类、Mapper接口以及XML文件。
以下是一个使用MyBatis Generator生成代码的简单示例:
一、pom.xml的依赖包:
<dependencies>
<!-- 其他依赖 -->
<!-- MyBatis Generator 依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
二、创建MyBatis Generator配置文件:在src/main/resources目录下创建一个generatorConfig.xml文件,用于配置生成器的参数:
<!-- generatorConfig.xml -->
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="default" targetRuntime="MyBatis3">
<!-- 数据库连接配置 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/your_database" userId="your_username" password="your_password"/>
<!-- 实体类生成位置 -->
<javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>
<!-- Mapper接口生成位置 -->
<sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/java"/>
<!-- XML文件生成位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>
<!-- 表配置 -->
<table tableName="users" domainObjectName="User"/>
</context>
</generatorConfiguration>
三、通过命令行或者IDE插件运行MyBatis Generator,生成代码:
mvn mybatis-generator:generate
资料来源:https://blog.csdn.net/weixin_47872288/article/details/135258686
文章评论