下面是详细讲解MyBatis实现增删改查的完整攻略:
1.添加MyBatis配置文件
在项目下创建mybatis-config.xml
配置文件,其中包含对mybatis
初始化相关配置信息,如数据源、别名、 mapper扫描等。
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig3.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/mybatis_test?useUnicode=true&characterEncoding=UTF8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/DeptMapper.xml"/>
</mappers>
</configuration>
2.添加映射文件
在resources
文件夹下创建com/example/mapper/DeptMapper.xml
文件,其中定义了具体的CRUD操作(例如:增删改查等),如下示例所示:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.DeptMapper">
<!-- 根据id查询部门 -->
<select id="getDeptById" parameterType="long" resultType="com.example.entity.Dept">
select * from dept where id=#{id}
</select>
<!-- 新增部门 -->
<insert id="addDept" parameterType="com.example.entity.Dept">
insert into dept(name,address) values(#{name},#{address})
</insert>
<!-- 更新部门 -->
<update id="updateDept" parameterType="com.example.entity.Dept">
update dept set name=#{name},address=#{address} where id=#{id}
</update>
<!-- 删除部门 -->
<delete id="deleteDeptById" parameterType="long">
delete from dept where id=#{id}
</delete>
</mapper>
3.添加实体类
public class Dept {
private Long id;
private String name;
private String address;
//getter and setter method
}
4.添加Mapper接口
public interface DeptMapper {
// 根据id查询部门
Dept getDeptById(Long id);
// 新增部门
int addDept(Dept dept);
// 更新部门
int updateDept(Dept dept);
// 删除部门
int deleteDeptById(Long id);
}
5. MyBatis映射接口和SQL语句的绑定
在applicationContext.xml
文件中,配置mybatis
的MapperScannerConfigurer
,例如:
<!-- 扫描Mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
6. 测试
//获取Spring上下文
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取Mapper
DeptMapper deptMapper = applicationContext.getBean(DeptMapper.class);
//查询
Dept dept = deptMapper.getDeptById(1L);
System.out.println(dept);
//新增
Dept dept1 = new Dept();
dept1.setName("test-1");
dept1.setAddress("address-1");
int addDept = deptMapper.addDept(dept1);
System.out.println(addDept);
//更新
dept.setAddress("updated-address");
int updateDept = deptMapper.updateDept(dept);
System.out.println(updateDept);
//删除
int deleteDept = deptMapper.deleteDeptById(1L);
System.out.println(deleteDept);
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Mybatis实现增删改查 - Python技术站