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>