实体类
public class comment {
private int commentId;
private String comcontent;
private String comtime;
private int newId;
public class news {
private int id;
private String title;
private String content;
private String resource;
private String time;
private List<comment> comment = new ArrayList<>();
list comment并不像hibernate实质性的保存数据
只有在连接查询时才有作用
所以添加多方时,list是无用的
下面看
插入一个新comment
public void insertcomment(int id,String comcontent,String comtime) {
SqlSession session = MybatisUtil.getSession();
commentMapper commentMapper=session.getMapper(commentMapper.class);
newsMapper newsMapper=session.getMapper(newsMapper.class);
List<news> list = newsMapper.selectone(id);
news a = list.get(0);
comment comment = new comment();
comment.setComcontent(comcontent);
comment.setComtime(comtime);
comment.setNewId(id);
commentMapper.addcomment(comment);
session.commit();
session.close();
}
实验打印list
每次只能打印当前保存的comment
对比hibernate 有session.save 所以可以存下数据
mybatis 都靠sql自行处理
查询所有
//连接查询所有
public void selectNAndCById(int id) {
SqlSession session = MybatisUtil.getSession();
commentMapper commentMapper=session.getMapper(commentMapper.class);
newsMapper newsMapper=session.getMapper(newsMapper.class);
news news = newsMapper.selectNAndCById(id);
List<comment> a = news.getComments();
for(comment b:a) {
System.out.println(b.toString());
}
System.out.println(news.toString());
}
这样就可以打印出所有
mapper.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="com.mapper.commentMapper">
<resultMap type="com.entity.comment" id="commentMap">
<id property="commentId" column="commentId"></id>
<result property="comtime" column="comtime"/>
<result property="comcontent" column="comcontent"/>
<result property="newId" column="newId"/>
</resultMap>
<insert id="addcomment" parameterType="com.entity.comment" useGeneratedKeys="true" keyProperty="commentId">
insert into comment(newId,comcontent,comtime) values (#{newId},#{comcontent},#{comtime})
</insert>
<select id="selectlike" resultType="com.entity.comment">select * from comment where newId = #{id} and comcontent like "%"#{keyword}"%"</select>
<delete id="deletecomment" >
delete from comment where newId in
<foreach item="acom" collection="list" open="(" close=")" separator=",">
#{acom.newId}
</foreach>
</delete>
</mapper>
package com.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.entity.comment;
import com.entity.news;
public interface commentMapper {
//增加
public void addcomment(comment comment);
//删除
public List<comment> selectlike(@Param("id") int id,@Param("keyword")String keyword);
public void deletecomment(List<comment> list);
}
多个参数应该加param(“a”) 对应#{a}