3
回答
hibernate主外键关联问题
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

hibernate主外键关联,有两张表news_info 和news_type 新闻信息表中的newtypeid外键与新闻类型表中的自增ID对应,请问在做插入news_info 表的时候 该怎么处理? 数据从前台获取

实体类中我使用的是ManyToOne 和 OneToMany 

ManyToOne对应NewsInfo.java 

OneToMany 对应NewsType.java

当我执行插入数据库的时候,插入的new_info表里面的字段newtypeid为null 


数据库两张表结构如下


CREATE TABLE `news_info` (
  `NEWS_ID` int(200) NOT NULL AUTO_INCREMENT COMMENT '新闻自动ID',
  `TITLE` varchar(100) DEFAULT NULL COMMENT '新闻标题',
  `SUMMARY` varchar(1000) DEFAULT NULL COMMENT '新闻摘要',
  `CONTENTS` varchar(5000) DEFAULT NULL COMMENT '新闻内容',
  `newsTypeID` int(10) DEFAULT NULL COMMENT '新闻类型ID与新闻类型表对应',
  `STATUS` int(1) NOT NULL COMMENT '状态0:已发布,1:未发布',
  `CREATER` int(10) DEFAULT NULL COMMENT '新闻发布人',
  `CREATED` date NOT NULL COMMENT '创建日期',
  `PMDATE` date NOT NULL COMMENT '发布日期',
  `MODIFYER` int(10) DEFAULT NULL COMMENT '修改人',
  `LASTMOD` date DEFAULT NULL COMMENT '修改日期',
  `DESCRIPTION` varchar(2000) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`NEWS_ID`),
  KEY `newsTypeID` (`newsTypeID`),
  CONSTRAINT `news_info_ibfk_1` FOREIGN KEY (`newsTypeID`) REFERENCES `news_type` (`PKTYPE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='新闻信息表';



CREATE TABLE `news_type` (
  `PKTYPE_ID` int(10) NOT NULL AUTO_INCREMENT COMMENT '新闻类型自动ID与新闻表类型对应',
  `NTYPE_NAME` varchar(100) NOT NULL COMMENT '新闻类型NAME',
  `PARENTID` int(10) NOT NULL COMMENT '级联父ID',
  `CDATE` date DEFAULT NULL COMMENT '日期',
  `DEL_FLAG` int(10) NOT NULL COMMENT 'flag:0 暂时未用到',
  PRIMARY KEY (`PKTYPE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='新闻类型表';


JSP页面 如下


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


<script type="text/javascript">  
    /* 初始化下载表格信息 */  
    $(function() {        
    // 下拉框选择控件,下拉框的内容是动态查询数据库信息  
    $('#newsTypeID').combobox({   
                url:'newsInfo/newsInfoAction!getNewsType.action',   
                editable:false, //不可编辑状态  
                cache: false,  
                panelHeight: 'auto',//自动高度适合  
                valueField:'ntypeid',     
                textField:'ntypeName',
                onLoadSuccess: function () { //加载完成后,设置选中第一项
                var val = $(this).combobox("getData");
                for (var item in val[0]) {
                    if (item == "ntypeid") {
                        $(this).combobox("select", val[0][item]);
                    }
                }
            }
           });   
    });  
</script>  
    
<script type="text/javascript">
	$(function() {
		$("#form").form({
			url :"newsInfo/newsInfoAction!persistenceNewsInfoDlg.action",
			onSubmit : function() {
				parent.$.messager.progress({
					title : '提示',
					text : '数据处理中,请稍后....'
				});
				var isValid = $(this).form('validate');
				if (!isValid) {
					parent.$.messager.progress('close');
				}
				return isValid;
			},
			success : function(result) {
				parent.$.messager.progress('close');
				result = $.parseJSON(result);
				if (result.status) {
					parent.reload;
					parent.$.modalDialog.openner.datagrid('reload');//之所以能在这里调用到parent.$.modalDialog.openner_datagrid这个对象,是因为role.jsp页面预定义好了
					parent.$.modalDialog.handler.dialog('close');
					parent.$.messager.show({
						title : result.title,
						msg : result.message,
						timeout : 1000 * 2
					});
				}else{
					parent.$.messager.show({
						title :  result.title,
						msg : result.message,
						timeout : 1000 * 2
					});
				}
			}
		});
	});
</script>

<div class="easyui-layout" data-options="fit:true,border:false">
	<div data-options="region:'center',border:false" title="" style="overflow: hidden;padding: 10px;">
		<form id="form" method="post">
			<fieldset>
				<legend><img src="extend/fromedit.png" style="margin-bottom: -3px;"/> 新闻编辑</legend>
				<input name="newsId" id="newsId"  type="hidden"/>
				<input name="created" id="created"  type="hidden"/>
				<input name="creater" id="creater"  type="hidden"/>
				<input name="status" id="status"  type="hidden"/>
            
				 <table>
					  <tr>
						<th>新闻标题</th>
						<td colspan="5"><textarea class="easyui-validatebox" name="title"  style="width: 415px;height: 25px;" data-options="required:true" ></textarea></td>
					</tr>
					 <tr>
					    <th>新闻摘要</th>
						<td><textarea class="easyui-validatebox" name="summary"  style="width: 415px;height: 30px;"></textarea></td>					 
					</tr>
					  <tr>
					    <th>新闻类型</th>
						<td><input id="newsTypeID" name="newsTypeID" class="easyui-textbox easyui-validatebox" value="0" required="required"/></td>
					 </tr>
					  <tr> 
						<th>新闻内容</th>
						<td colspan="3"><textarea class="easyui-kindeditor" name="contents"  style="width: 415px;height: 80px;" data-options="required:true"></textarea></td>
					</tr>
					 <!--  <tr> 
						<th>备注</th>
						<td colspan="3"><textarea class="easyui-validatebox" name="description"  style="width: 415px;height: 50px;"></textarea></td>
					</tr>-->
				 </table>
			</fieldset>
		</form>
	</div>
</div>




ACTION代码如下

public String persistenceNewsInfoDlg() throws Exception
	{
		List<NewsInfo> list=new ArrayList<NewsInfo>();
		list.add(getModel());
		Integer newsId = getModel().getNewsId();
		if (null==newsId||"".equals(newsId))
		{
			OutputJson(getMessage(newsInfoService.addNewsInfo(list)), Constants.TEXT_TYPE_PLAIN);
		}else {
			OutputJson(getMessage(newsInfoService.updNewsInfo(list)), Constants.TEXT_TYPE_PLAIN);
		}
		return null;
	}



service代码如下 

public boolean addNewsInfo(List<NewsInfo> addlist) {
		System.out.println("-------addNewsInfo------------" + addlist.size());
		logger.debug("addNewsInfo");
		//NewsType newsType = (NewsType)newsTyDao.get(NewsType.class, typeId);
		if (addlist != null && addlist.size() != 0) {
			ShiroUser users = Constants.getCurrendUser();
			for (NewsInfo newsInfo : addlist) {
				newsInfo.setCreated(new Date());
				newsInfo.setPmdate(new Date());
				newsInfo.setLastmod(new Date());
				newsInfo.setStatus(0);
				//newsInfo.setNewsType(newsType);
				
				if (users != null) {
					newsInfo.setCreater(users.getUserId());
					System.out.println("------" + users.getUserId());
					newsInfo.setModifyer(users.getUserId());
				}
				publicDao.save(newsInfo);
			}
		}
		return true;
	}



实体类代码如下:

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

/**
 * Role entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "NEWS_TYPE", catalog = "NEWS")
@DynamicUpdate(true)
@DynamicInsert(true)
public class NewsType implements java.io.Serializable
{
	private static final long serialVersionUID = -5864236036218164207L;
	private Integer typeId;
	private String typeName;
	private Integer parentId;
	private Date cdate;
	private Integer delFlag;
	private Set<NewsInfo> newsInfo = new HashSet<NewsInfo>(0);

	// Constructors

	/** default constructor */
	public NewsType()
	{
	}

	/** full constructor */
	public NewsType(String typeName, Integer parentId,
			Date cdate, Integer delFlag, Set<NewsInfo> newsInfo) {
		this.typeName = typeName;
		this.parentId = parentId;
		this.cdate = cdate;
		this.delFlag = delFlag;
		this.newsInfo = newsInfo;
	}

	// Property accessors
	@Id
	@GeneratedValue
	@Column(name = "PKTYPE_ID", unique = true, nullable = false)
	public Integer getTypeId()
	{
		return this.typeId;
	}

	public void setTypeId(Integer typeId )
	{
		this.typeId = typeId;
	}

	@Column(name = "NTYPE_NAME")
	public String getTypeName()
	{
		return this.typeName;
	}

	public void setTypeName(String typeName )
	{
		this.typeName = typeName;
	}


	@Column(name = "PARENTID")
	public Integer getParentId()
	{
		return this.parentId;
	}

	public void setParentId(Integer parentId )
	{
		this.parentId = parentId;
	}
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "CDATE")
	public Date getCdate()
	{
		return this.cdate;
	}

	public void setCdate(Date cdate )
	{
		this.cdate = cdate;
	}

	

	@Column(name = "DEL_FLAG")
	public Integer getDelFlag()
	{
		return this.delFlag;
	}

	public void setDelFlag(Integer delFlag )
	{
		this.delFlag = delFlag;
	}


	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "newsType")
	public Set<NewsInfo> getNewsType()
	{
		return this.newsInfo;
	}

	public void setNewsType(Set<NewsInfo> newsInfo )
	{
		this.newsInfo = newsInfo;
	}
}



import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import com.erp.util.ExcelVOAttribute;

/**
 * NewsInfo entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "NEWS_INFO", catalog = "NEWS")
@DynamicUpdate(true)
@DynamicInsert(true)
public class NewsInfo implements java.io.Serializable {

	private static final long serialVersionUID = 5912663721736234567L;
	private Integer newsId;
	@ExcelVOAttribute(name = "新闻标题", column = "A", isExport = true, prompt = "这是新闻标题!")
	private String title;
	@ExcelVOAttribute(name = "新闻摘要", column = "B")
	private String summary;
	@ExcelVOAttribute(name = "新闻内容", column = "C")
	private String contents;
	@ExcelVOAttribute(name = "新闻类型", column = "D")
	private Integer status;
	private Integer creater;
	private Date created;

	@ExcelVOAttribute(name = "发布时间", column = "E")
	private Date pmdate;

	private Integer modifyer;
	private Date lastmod;

	@ExcelVOAttribute(name = "备注", column = "F")
	private String description;

	private NewsType newsType;

	// Constructors

	/** default constructor */
	public NewsInfo() {
	}

	/** minimal constructor */
	public NewsInfo(Integer status, Date created) {
		this.status = status;
		this.created = created;
	}

	/** full constructor */
	public NewsInfo(Integer newsId, String title, String summary, String contents,
			Integer status, Integer creater, Date created, Date pmdate,
			Integer modifyer, Date lastmod, String description,NewsType newsType) {
		this.newsId = newsId;
		this.title = title;
		this.summary = summary;
		this.contents = contents;
		this.status = status;
		this.creater = creater;
		this.created = created;
		this.pmdate = pmdate;
		this.modifyer = modifyer;
		this.lastmod = lastmod;
		this.description = description;
		this.newsType = newsType;
	}

	// Property accessors
	@Id
	@GeneratedValue
	@Column(name = "NEWS_ID", unique = true, nullable = false)
	public Integer getNewsId() {
		return this.newsId;
	}

	public void setNewsId(Integer newsId) {
		this.newsId = newsId;
	}

	@Column(name = "TITLE")
	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Column(name = "SUMMARY")
	public String getSummary() {
		return this.summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	@Column(name = "CONTENTS")
	public String getContents() {
		return this.contents;
	}

	public void setContents(String contents) {
		this.contents = contents;
	}

	@Column(name = "STATUS")
	public Integer getStatus() {
		return this.status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	@Column(name = "CREATER")
	public Integer getCreater() {
		return this.creater;
	}

	public void setCreater(Integer creater) {
		this.creater = creater;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "CREATED")
	public Date getCreated() {
		return this.created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "PMDATE")
	public Date getPmdate() {
		return this.pmdate;
	}

	public void setPmdate(Date pmdate) {
		this.pmdate = pmdate;
	}

	@Column(name = "MODIFYER")
	public Integer getModifyer() {
		return this.modifyer;
	}

	public void setModifyer(Integer modifyer) {
		this.modifyer = modifyer;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "LASTMOD")
	public Date getLastmod() {
		return this.lastmod;
	}

	public void setLastmod(Date lastmod) {
		this.lastmod = lastmod;
	}

	@Column(name = "DESCRIPTION")
	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	@JoinColumn(name = "newsTypeID")
	public NewsType getNewsType() {
		return this.newsType;
	}

	public void setNewsType(NewsType newsType) {
		this.newsType = newsType;
	}

}




举报
小0
发帖于2年前 3回/209阅
共有3个答案 最后回答: 2年前
action的getModel()里new一个NewsType填上newsTypeID, 给newsInfo setNewsType, 然后在service里检查这个newsTypeIDNewsType是否存在于数据库里, 存在就保存, 不存在就向前台报错.
--- 共有 3 条评论 ---
wuyiw回复 @小0 : 将页面的newsTypeID赋给newsType的typeId, 然后将这个newsType赋给newsInfo的newsType 2年前 回复
小0报错: Unexpected Exception caught setting 'newsTypeId' on 'class com.erp.action.NewsInfoAction: Error setting expression 'newsTypeId' with value ['1', ] 2年前 回复
小0这个newsTypeID 我在实体类里面没有这个属性 怎么set到NewsType里? 2年前 回复

大概是这样:

NewsType newsType = new NewsType();
newsType.setTypeId(Integer.valueOf(request.getParameter('newsTypeId')));
newsInfo.setNewsType(newsType);



顶部