在使用 MyBatis 进行持久层开发时,实体类通常需要提供一个无参构造器。这是因为 MyBatis 在映射结果集到实体对象时,会通过反射调用无参构造器来创建对象实例。如果实体类没有无参构造器,MyBatis 将无法创建对象,从而导致运行时错误。
以下是一个简单的示例,展示如何在实体类中定义无参构造器,并使用 MyBatis 进行基本的 CRUD 操作。
实体类
假设有一个 User
实体类,包含 id
、name
和 email
属性:
public class User {
private Integer id;
private String name;
private String email;
// 无参构造器
public User() {
}
// 全参构造器(可选)
public User(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getter 和 Setter 方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
MyBatis 配置
MyBatis 配置文件 mybatis-config.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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="your_username"/>
<property name="password" value="your_password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
Mapper 接口 UserMapper.java
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<User> getAllUsers();
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(@Param("id") Integer id);
@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
@Update("UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM users WHERE id = #{id}")
int deleteUser(@Param("id") Integer id);
}
Mapper XML 文件 UserMapper.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="UserResultMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
</resultMap>
<select id="getAllUsers" resultMap="UserResultMap">
SELECT * FROM users
</select>
<select id="getUserById" parameterType="int" resultMap="UserResultMap">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO users(name, email) VALUES(#{name}, #{email})
</insert>
<update id="updateUser" parameterType="com.example.entity.User">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
使用示例
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Main {
public static void main(String[] args) {
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
// 插入新用户
User newUser = new User(null, "Alice", "alice@example.com");
userMapper.insertUser(newUser);
session.commit();
// 查询所有用户
List<User> users = userMapper.getAllUsers();
for (User user : users) {
System.out.println(user);
}
// 更新用户
newUser.setName("Alicia");
userMapper.updateUser(newUser);
session.commit();
// 删除用户
userMapper.deleteUser(newUser.getId());
session.commit();
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
总结
- 无参构造器:实体类必须提供一个无参构造器,以便 MyBatis 可以通过反射创建对象实例。
- MyBatis 配置:配置 MyBatis 的数据源和映射文件。
- Mapper 接口和 XML 文件:定义 SQL 语句和映射关系。
- 使用示例:通过 SqlSession 获取 Mapper 对象,执行 CRUD 操作。