mybatis---表和實體類不匹配問題
阿新 • • 發佈:2019-01-26
1.表和實體類不匹配
資料庫建表(標準格式為下劃線連線,與實體類有差異時)
create table teacher (
id int primary key auto_increment,
first_name varchar(20),
last_name varchar(20)
);
<!-- 方法1: 可以使用列別名來解決不一致問題 -->
<select id="selectOne" parameterType="int" resultType="com.westos.entity.Teacher">
select id,first_name firstName,last_name lastName from teacher where id = #{id}
</ select>
<!-- 方法2: 使用 resultMap 代替 resultType完成對映 -->
<select id="selectOne" parameterType="int" resultMap="aaa">
select id, first_name, last_name from teacher where id = #{id}
</select>
<!-- type="實體物件的型別"
id 標籤用來對映主鍵
result 標籤用來對映其它列
-->
<resultMap id="aaa" type= "com.westos.entity.Teacher">
<!-- column="列名" property="屬性名" -->
<id column="id" property="id"></id>
<result column="first_name" property="firstName"></result>
<result column="last_name" property="lastName"></result>
</resultMap>
2.建議使用 resultMap 代替 resultType完成對映 (功能更強大,是別名滿足不了的)
例如:
連線查詢的對映
商品和類別
select * from product p inner join category c on p.category_id = c.id where p.id=1;
<!-- 把連線查詢對映到兩個有關係的實體類上 -->
<select id="selectById" parameterType="int" resultMap="bbb">
select p.id, p.name, p.price, c.id cid, c.name cname
from product p inner join category c on p.category_id = c.id where p.id=#{id}
</select>
<!-- association 關聯 -->
<resultMap id="bbb" type="com.westos.entity.Product">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="price" property="price"></result>
<!-- property="關係屬性名" -->
<association property="category" javaType="com.westos.entity.Category">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
</association>
</resultMap>
Java程式碼如下
@Test
public void testproduct() {
SqlSession sqlSession = factory.openSession();
Product p = sqlSession.selectOne("com.westos.mapper.ProductMapper.selectById", 1);
System.out.println(p);
System.out.println(p.getCategory());
}