使用mybatis来操作oracle
1.使用spring的初始化工具来构建项目
2.添加依赖
3.项目结构
4.详细文件
4.1配置文件
server:
port: 8888
spring:
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1:11521:helowin
username: mark
password: 123456
flyway:
enabled: false
4.2DTO
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto implements Serializable {
private Integer id;
private String name;
private String pwd;
}
4.3Controller
@RestController
@RequestMapping("/hel")
public class HelloOracle {
@Autowired
private UserService userService;
@GetMapping("/user")
public List<UserDto> getUsers(){
List<UserDto> users= userService.getAllUsers();
return users;
}
}
4.4Service
public interface UserService {
/**
* 获取所有用户
* @return
*/
List<UserDto> getAllUsers();
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public List<UserDto> getAllUsers() {
List<UserDto> users=userDao.selectAllUsers();
return users;
}
}
4.5Dao
@Mapper
public interface UserDao {
/**
* 获取所有用户
* @return
*/
List<UserDto> selectAllUsers();
}
4.6Mapper
<?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.oraclewithmybatis.dao.UserDao">
<!-- 配置查询所有 id为方法名 resultType指定封装的实体类型-->
<select id="selectAllUsers" resultType="com.example.oraclewithmybatis.dto.UserDto">
select
ID id,
PWD pwd,
USER_NAME name
from USER_INFO
</select>
</mapper>
4.7Sql脚本
CREATE TABLE USER_INFO(
ID INT NOT NULL AUTO_INCREMENT COMMENT 'ID' ,
PWD VARCHAR(200) NOT NULL COMMENT '密码' ,
USER_NAME VARCHAR(200) NOT NULL COMMENT '用户名' ,
PRIMARY KEY (ID)
) COMMENT = '用户表';
4.8测试结果
GET http://localhost:8888/hel/user
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 25 Oct 2021 13:14:56 GMT
Keep-Alive: timeout=60
Connection: keep-alive
[
{
"id": 1,
"name": "mark",
"pwd": "123456"
},
{
"id": 2,
"name": "张安",
"pwd": "123456"
}
]
Response code: 200; Time: 1040ms; Content length: 75 bytes