通過mybatis添加數據記錄時,如何返回主鍵
阿新 • • 發佈:2018-04-30
通過mybatis添加數據記錄時如何返java
private SqlSession session = null; @BeforeClass public void init() throws IOException { // SqlSession--->SqlSessionFatory----->SqlSessionFatoryBuilder SqlSessionFactoryBuilder ssb = new SqlSessionFactoryBuilder(); InputStream ins = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory ssf = ssb.build(ins); session = ssf.openSession(); } public static void main(String[] args) throws IOException { SqlSessionFactoryBuilder ssb = new SqlSessionFactoryBuilder(); InputStream ins = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory ssf = ssb.build(ins); SqlSession session = ssf.openSession(); User user = session.selectOne("cn.java.dao.impl.One2ManyImpl.one2Many"); System.out.println(user); } @Test public void one2Many() { User user = session.selectOne("cn.java.dao.impl.One2ManyImpl.one2Many"); System.out.println(user); }a @Test public void addUser() { User user = new User(); user.setPassword("456"); user.setUsername("aaa"); System.out.println(user); int result = session.insert("cn.java.dao.impl.One2ManyImpl.addUser", user); // session.commit(); System.out.println("result=" + result);// result代表的是影響的行數 System.out.println("當前插入數據的主鍵為=" + user.getId()); } @Test public void userAdd() { Map<String, Object> map = new HashMap<String, Object>(); int result = session.insert("cn.java.dao.impl.One2ManyImpl.userAdd", map); session.commit(); System.out.println("result=" + result);// result代表的是影響的行數 System.out.println("當前插入數據的主鍵為=" + map.get("id"));
xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.java.dao.impl.One2ManyImpl" > <resultMap id="BaseResultMap" type="cn.java.entity.User" > <result property="id" javaType="Long" column="id"/> <result property="username" javaType="String" column="username"/> <result property="password" javaType="String" column="password"/> <collection property="orderList" ofType="cn.java.entity.Order"> <id column="orderId" property="orderid" jdbcType="BIGINT" /> <result column="orderName" property="ordername" jdbcType="VARCHAR" /> <result column="price" property="price" jdbcType="REAL" /> <result column="userId" property="userid" jdbcType="BIGINT" /> </collection> </resultMap> <select id="one2Many" resultMap="BaseResultMap"> select * from users u inner join orders o on u.id=o.`userId` </select> <!-- useGeneratedKeys:使用主鍵作為返回值 keyProperty:將主鍵值封裝到某一個實體類中對應的屬性中 --> <insert id="addUser" useGeneratedKeys="true" parameterType="cn.java.entity.User" keyProperty="id"> INSERT INTO users SET username=#{username},PASSWORD=#{password} </insert> <insert id="userAdd" useGeneratedKeys="true" keyProperty="id" parameterType="Map"> INSERT INTO users SET username=‘xxx‘,PASSWORD=‘xxx‘ </insert> </mapper>
通過mybatis添加數據記錄時,如何返回主鍵