oracle 整合 mybatis 批量添加 例子
时间: 2023-11-09 13:12:00 浏览: 88
以下是一个使用 Oracle 和 MyBatis 的批量添加示例:
1. 创建一个 Employee 类,表示要添加到数据库中的员工:
```
public class Employee {
private int id;
private String name;
private String position;
private int salary;
// 省略 getter 和 setter
}
```
2. 创建一个 Mapper 接口,定义添加操作:
```
public interface EmployeeMapper {
void addEmployees(List<Employee> employees);
}
```
3. 创建一个 XML 映射文件,指定 SQL 语句和参数映射:
```
<insert id="addEmployees" parameterType="java.util.List">
<foreach collection="list" item="employee" separator=";">
INSERT INTO employees (id, name, position, salary)
VALUES (#{employee.id}, #{employee.name}, #{employee.position}, #{employee.salary})
</foreach>
</insert>
```
4. 在 MyBatis 配置文件中添加数据源和 Mapper:
```
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE"/>
<property name="username" value="your_username"/>
<property name="password" value="your_password"/>
</dataSource>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
```
5. 在代码中使用 Mapper 执行批量添加操作:
```
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "John", "Manager", 50000));
employees.add(new Employee(2, "Jane", "Developer", 30000));
employees.add(new Employee(3, "Bob", "Designer", 25000));
employeeMapper.addEmployees(employees);
sqlSession.commit();
sqlSession.close();
```
注意,需要手动提交事务。
阅读全文