<insert id="addUser" parameterType="com.example.User">
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Long">
SELECT user_seq.NEXTVAL FROM dual
</selectKey>
INSERT INTO user(id, name, age) VALUES (#{id}, #{name}, #{age}) RETURNING id INTO #{id}
</insert>
public interface UserMapper {
<insert id="addUser" parameterType="com.example.User">
INSERT INTO user(name, age) VALUES (#{name}, #{age})
</insert>
}
public interface UserMapper2 {
<select id="getId" resultType="java.lang.Long">
SELECT user_seq.NEXTVAL FROM dual
</select>
}
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserMapper2 userMapper2;
public void addUser(User user) {
// 先取出 id 值
Long id = userMapper2.getId();
// 將 id 值賦給插入數據的主鍵屬性
user.setId(id);
// 再插入數據
userMapper.addUser(user);
}
}