不使用mybatis-plus呢
时间: 2024-01-25 17:10:25 浏览: 145
spring-boot-mybatis-plus 一套打通 有注释 打开就可使用
不使用MyBatis-Plus的话,可以使用原生的MyBatis框架来进行数据库操作。MyBatis是一个开源的持久层框架,它支持自定义SQL、存储过程以及高级映射。以下是一个使用MyBatis进行数据库操作的例子:
1. 配置文件mybatis-config.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
```
2. 实体类User.java
```java
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
```
3. Mapper接口UserMapper.java
```java
public interface UserMapper {
User selectUserById(Long id);
List<User> selectAllUsers();
void insertUser(User user);
void updateUser(User user);
void deleteUserById(Long id);
}
```
4. Mapper映射文件UserMapper.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.UserMapper">
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="selectUserById" resultMap="userMap">
select * from user where id = #{id}
</select>
<select id="selectAllUsers" resultMap="userMap">
select * from user
</select>
<insert id="insertUser">
insert into user(name, age) values(#{name}, #{age})
</insert>
<update id="updateUser">
update user set name=#{name}, age=#{age} where id=#{id}
</update>
<delete id="deleteUserById">
delete from user where id=#{id}
</delete>
</mapper>
```
5. 使用MyBatis进行数据库操作
```java
public class MyBatisDemo {
public static void main(String[] args) {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectUserById(1L);
System.out.println(user.getName());
List<User> userList = userMapper.selectAllUsers();
for (User u : userList) {
System.out.println(u.getName());
}
User newUser = new User();
newUser.setName("Tom");
newUser.setAge(20);
userMapper.insertUser(newUser);
newUser.setName("Jerry");
newUser.setAge(21);
userMapper.updateUser(newUser);
userMapper.deleteUserById(2L);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
```
阅读全文