四 mybatis获取主键列的值(orcale)

来源:互联网 发布:火星哥 知乎 编辑:程序博客网 时间:2024/06/06 17:04
建一个实体类,类属性为表中的列名 ***

接口映射xml

1.接口定义
public interface FoodInter {
public abstract void saveFood(Food food);

}

2.Mapper.xml:
//获取主键列的值
<insert id="saveFood">
  <!--  keyProperty :属性名(区分大小写)-->
<selectKey keyProperty="foodId" order="BEFORE" resultType="int" statementType="STATEMENT">
select foods_scr.nextval from dual
</selectKey>
insert into foods values(#{foodId},#{foodName},#{price})
</insert>
   
3.测试方法:

private  SqlSession getSession() throws IOException {
// mybatis核心配置文件路径
String resource = "cn/et/lesson2/xml/mybatis.xml";


InputStream inputStream = Resources.getResourceAsStream(resource);
// 工厂类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// session操作的是指向sql语句的一个唯一标识符
SqlSession openSession = sqlSessionFactory.openSession();
return openSession;
}

@Test
public  void saveFood() throws IOException {
SqlSession openSession = getSession();

FoodInter mapper = openSession.getMapper(FoodInter.class);

Food food=new Food();

food.setFoodName("kkk");
food.setPrice("55");

mapper.saveFood(food);

openSession.commit();

System.out.println(food.getFoodId());
}

接口映射注解

1.接口定义:
public interface FoodInter {

@SelectKey(before=true,keyProperty="foodId",statement="select foods_scr.nextval from dual", resultType = int.class)
@Insert("insert into foods values(#{foodId},#{foodName},#{price})")
public abstract void saveFood(Food food);

}


2.测试方法:
private  SqlSession getSession() throws IOException {
// mybatis核心配置文件路径
String resource = "cn/et/lesson2/xml/mybatis.xml";


InputStream inputStream = Resources.getResourceAsStream(resource);
// 工厂类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// session操作的是指向sql语句的一个唯一标识符
SqlSession openSession = sqlSessionFactory.openSession();
return openSession;
}


@Test
public  void saveFood() throws IOException {

SqlSession openSession = getSession();

FoodInter mapper = openSession.getMapper(FoodInter.class);

Food food=new Food();

food.setFoodName("kkk");
food.setPrice("55");

mapper.saveFood(food);

openSession.commit();

System.out.println(food.getFoodId());
}