在MyBatis中,要实现在插入数据后返回主键,可以在Mapper的XML文件中使用useGeneratedKeys属性和keyProperty属性。以下是一个示例:
首先,确保你的Oracle表有一个可以自动生成主键的字段,比如使用Oracle的序列。
CREATE TABLE example_table (id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,name VARCHAR2(100),PRIMARY KEY (id)
);CREATE SEQUENCE example_table_seq START WITH 1 INCREMENT BY 1;
然后,在MyBatis的Mapper XML文件中,你可以这样配置:
<insert id="insertExample" useGeneratedKeys="true" keyProperty="id">SELECT example_table_seq.NEXTVAL FROM DUAL;INSERT INTO example_table (id, name)VALUES (example_table_seq.CURRVAL, #{name})
</insert>
或者
<mapper namespace="com.example.mapper.YourMapper"> <!-- 假设你有一个名为YOUR_SEQ的Oracle序列 --> <insert id="insertYourEntity" parameterType="com.example.entity.YourEntity"> <!-- 先使用selectKey获取序列的下一个值 --> <selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE"> SELECT YOUR_SEQ.NEXTVAL FROM DUAL </selectKey> <!-- 然后将获取到的序列值作为主键插入到表中 --> INSERT INTO your_table (id, column1, column2, ...) VALUES (#{id}, #{property1}, #{property2}, ...) </insert> </mapper>
这里的useGeneratedKeys设置为true表示我们想要获取数据库生成的主键,keyProperty设置为Java对象中的属性名,用于存储主键值。
在Java代码中,你的Mapper接口可能看起来像这样:
public interface ExampleMapper {int insertExample(Example example);
}public class Example {private int id;private String name;// getters and setters
}
当你调用insertExample方法并传入一个Example对象时,插入操作执行后,MyBatis会自动将生成的主键值设置到这个对象的id属性中。