[关于插入更新数据] 各位大哥大姐大叔大婶走过路过不要错过的帮我来看看这个入门问题各位大哥大姐大叔大婶走过路过的帮我来看看这个入门问题
是这样 在这个addFeed中大家可以看到
mFeed.add(service.loadFeed(feed.getId()));
这句 我估计就是这句的问题,详细情况是这样的:
我要做一个在线RSS的订阅系统 其中用户可以添加Feed,
现在是当用户添加Feed后可以在Feed表中出现刚添加的Feed名称以及URL
但是在 Feed 与 Member 的链接表(Feed 与 Member 为多对多关系)r_feed_member中就没有信息
我尝试了吧我想到的可能相关的代码都发上来了
有点多,辛苦大家了!主要我还是初学java 实在搞不清。谢谢public ActionForward addFeed(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ActionMessages msgs = new ActionMessages();
List feedList = null;
FeedService service = new FeedServiceImpl();
int pageNo = 1; //页号
int pageSize = 6; //每页记录数
int totals = 0; //记录总数
int totalPages = 0; //总页数
if (request.getParameter("pageNo")!=null)pageNo = Integer.parseInt(request.getParameter("pageNo"));
try{
//判断会员是否已成功登录
Member mem = (Member)request.getSession().getAttribute("member");
if(mem==null){
msgs.add("addFeedStatus",new ActionMessage(Constants.WORD_ADD_WARNING_KEY));
}else{
boolean status = false;
String name = request.getParameter("name");
String url = request.getParameter("url");
Feed feed = new Feed();
feed.setName(name.trim());
feed.setUrl(url.trim());
status = service.addFeed(feed);
Set mFeed = new HashSet();
mFeed.add(service.loadFeed(feed.getId()));
mem.setFeed(mFeed);
if (status){
msgs.add("addFeedStatus",new ActionMessage(Constants.WORD_ADD_SUC_KEY));
}else{
msgs.add("addFeedStatus",new ActionMessage(Constants.WORD_ADD_FAIL_KEY));
}
}
saveErrors(request, msgs);
feedList = service.browseFeed(pageSize, pageNo);
totals = service.countFeed();
if (feedList!=null&&feedList.size()>0)request.setAttribute("feedList", feedList);
//设置总记录数、总页数、当前页号
totalPages = totals / pageSize;
if ((totals % pageSize)>0) totalPages++; 
request.setAttribute("totals",new Integer(totals).toString());
request.setAttribute("totalPages",new Integer(totalPages).toString());
request.setAttribute("pageNo",new Integer(pageNo).toString());
}catch(Exception ex){
logger.info("在执行MemAction类中的addFeed方法时出错:\n");
ex.printStackTrace();
}
return mapping.findForward("browseFeed");
}
public class FeedServiceImpl extends BaseLog implements FeedService {
public boolean addFeed(Feed feed) throws Exception {
Session session = MySessionFactory.getSession();
Transaction tx = null;
boolean status = false;
try{
tx = session.beginTransaction();
session.save(feed);
tx.commit();
status=true;
}catch(Exception ex){
if(tx!=null)tx.rollback();
logger.info("在执行FeedServiceImpl类中的addFeed方法时出错:\n");
ex.printStackTrace();
}finally{
MySessionFactory.closeSession();
}
return status;
}
下面是ORM的信息 其中 Feed 与 Member 是多对多的关系 中间有一张 r_feed_member表和他们链接
public class Feed implements java.io.Serializable {
// Fields
private Integer id;
private String url;

private String name;

private Set item = new HashSet();

private Set member = new HashSet();
// Constructors
/** default constructor */
public Feed() {
}
/** full constructor */
public Feed(String url) {
this.url = url;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Set getItem() {
return item;
}
public void setItem(Set item) {
this.item = item;
}
public Set getMember() {
return member;
}
public void setMember(Set member) {
this.member = member;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Member implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
private Date created;
private Date lastLogin;
private Integer loginTimes;
private String emailAddr;

private Set feed = new HashSet();

private Set tag = new HashSet();
// Constructors
/** default constructor */
public Member() {
}
/** minimal constructor */
public Member(String username, String password) {
this.username = username;
this.password = password;
}
/** full constructor */
public Member(String username, String password, Date created,
Date lastLogin, Integer loginTimes, String emailAddr) {
this.username = username;
this.password = password;
this.created = created;
this.lastLogin = lastLogin;
this.loginTimes = loginTimes;
this.emailAddr = emailAddr;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLastLogin() {
return this.lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Integer getLoginTimes() {
return this.loginTimes;
}
public void setLoginTimes(Integer loginTimes) {
this.loginTimes = loginTimes;
}
public String getEmailAddr() {
return this.emailAddr;
}
public void setEmailAddr(String emailAddr) {
this.emailAddr = emailAddr;
}

public Set getTag() {
return tag;
}
public void setTag(Set tag) {
this.tag = tag;
}
public Set getFeed() {
return feed;
}
public void setFeed(Set feed) {
this.feed = feed;
}
}

解决方案 »

  1.   

    public boolean addFeed(Feed feed) throws Exception { 
    Session session = MySessionFactory.getSession(); 
    Transaction tx = null; 
    boolean status = false; MySessionFactory是什么东东
      

  2.   

    那是session工厂public boolean addFeed(Feed feed) throws Exception { 
    Session session = MySessionFactory.getSession(); 
    Transaction tx = null; 
    boolean status = false; 
    try{ 
    tx = session.beginTransaction(); 
    session.save(feed); 
    tx.commit(); 
    status=true; 
    }catch(Exception ex){ 
    if(tx!=null)tx.rollback(); 
    logger.info("在执行FeedServiceImpl类中的addFeed方法时出错:\n"); 
    ex.printStackTrace(); 
    }finally{ 
    MySessionFactory.closeSession(); 

    return status; 

    这段代码只完成了 feed对象的提交 ,在哪里体现提交这个对象的同时可以提交另一个对象呢?我也是初学
      

  3.   

    补充: 你的loadfeed方法在哪?
      

  4.   

    各位现在最主要的问题就是没有错误提示啊
    MySessionFactorypublic class MySessionFactory {    /** 
         * Location of hibernate.cfg.xml file.
         * Location should be on the classpath as Hibernate uses  
         * #resourceAsStream style lookup for its configuration file. 
         * The default classpath location of the hibernate config file is 
         * in the default package. Use #setConfigFile() to update 
         * the location of the configuration file for the current session.   
         */
        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal threadLocal = new ThreadLocal();
        private static Configuration configuration = new Configuration();
        private static org.hibernate.SessionFactory sessionFactory;
        private static String configFile = CONFIG_FILE_LOCATION; static {
         try {
    configuration.configure(configFile);
    sessionFactory = configuration.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
    }
        }
        private MySessionFactory() {
        }

    /**
         * Returns the ThreadLocal Session instance.  Lazy initialize
         * the <code>SessionFactory</code> if needed.
         *
         *  @return Session
         *  @throws HibernateException
         */
        public static Session getSession() throws HibernateException {
            Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
    if (sessionFactory == null) {
    rebuildSessionFactory();
    }
    session = (sessionFactory != null) ? sessionFactory.openSession()
    : null;
    threadLocal.set(session);
    }        return session;
        } /**
         *  Rebuild hibernate session factory
         *
         */
    public static void rebuildSessionFactory() {
    try {
    configuration.configure(configFile);
    sessionFactory = configuration.buildSessionFactory();
    } catch (Exception e) {
    System.err
    .println("%%%% Error Creating SessionFactory %%%%");
    e.printStackTrace();
    }
    } /**
         *  Close the single hibernate session instance.
         *
         *  @throws HibernateException
         */
        public static void closeSession() throws HibernateException {
            Session session = (Session) threadLocal.get();
            threadLocal.set(null);        if (session != null) {
                session.close();
            }
        } /**
         *  return session factory
         *
         */
    public static org.hibernate.SessionFactory getSessionFactory() {
    return sessionFactory;
    } /**
         *  return session factory
         *
         * session factory will be rebuilded in the next call
         */
    public static void setConfigFile(String configFile) {
    MySessionFactory.configFile = configFile;
    sessionFactory = null;
    } /**
         *  return hibernate configuration
         *
         */
    public static Configuration getConfiguration() {
    return configuration;
    }
    }
    loadfeed
    /** 装载Feed */
    public Feed loadFeed(Integer id) throws Exception {
    Session session = MySessionFactory.getSession();
    Transaction tx = null;
    Feed feed = null;
    try{
    tx = session.beginTransaction();
    feed = (Feed)session.get(Feed.class, id);
    tx.commit();
    }catch(Exception ex){
    if(tx!=null)tx.rollback();
    logger.info("在执行FeedServiceImpl类中的loadFeed方法时出错:\n");
    ex.printStackTrace();
    }finally{
    MySessionFactory.closeSession();
    }
    return feed;
    }这里是我觉得写到member的部分 是不是不该这么写啊Set mFeed = new HashSet();
    mFeed.add(service.loadFeed(feed.getId()));
    mem.setFeed(mFeed); 
      

  5.   

    将laze="false";或//加下面的一句
    Hibernate.initialize(service.loadFeed(feed.getId()));mFeed.add(service.loadFeed(feed.getId())); 
    mem.setFeed(mFeed); 
    试下看.....
      

  6.   

    哥们 2个方法都是了 还是一样
    下面是我的orm 的xml 文件
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="com.feelergo.ORM.Member" table="member" catalog="feelergo">
            <id name="id" type="java.lang.Integer">
                <column name="id" />
                <generator class="identity" />
            </id>
            <property name="username" type="java.lang.String">
                <column name="username" length="18" not-null="true" />
            </property>
            <property name="password" type="java.lang.String">
                <column name="password" length="40" not-null="true" />
            </property>
            <property name="created" type="java.util.Date">
                <column name="created" length="19" />
            </property>
            <property name="lastLogin" type="java.util.Date">
                <column name="lastLogin" length="19" />
            </property>
            <property name="loginTimes" type="java.lang.Integer">
                <column name="loginTimes" />
            </property>
            <property name="emailAddr" type="java.lang.String">
                <column name="emailAddr" length="100" />
            </property>
            <!--映射Member到Tag的一对多双向关联-->
            <set name="tag" 
     cascade="all"
     lazy="false"
     inverse="true">
             <key column="member_id"/>
             <one-to-many class="com.feelergo.ORM.Tag" />
            </set>
            <!--映射Member到Feed的多对多双向关联-->
            <set name="feed" table="r_member_feed" lazy="false" cascade="save-update">
             <key column="member_id"/>
             <many-to-many class="com.feelergo.ORM.Feed" column="feed_id"/>
            </set>   
        </class>
    </hibernate-mapping><?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="com.feelergo.ORM.Feed" table="feed" catalog="feelergo">
            <id name="id" type="java.lang.Integer">
                <column name="id" />
                <generator class="identity" />
            </id>
            <property name="url" type="java.lang.String">
                <column name="url" length="100" not-null="true" />
            </property>
            <property name="name" type="java.lang.String">
                <column name="name" length="50" not-null="true" />
            </property>
            <!--映射Feed到Item的一对多双向关联-->
            <set name="item" 
     cascade="all"
     lazy="false"
     inverse="true">
             <key column="feed_id"/>
             <one-to-many class="com.feelergo.ORM.Item" />
            </set>
            <!--映射Feed到Member的多对多双向关联-->
            <set name="Member" 
           table="r_member_feed" 
           lazy="false" 
                 inverse="true" 
                 cascade="save-update">
             <key column="feed_id"/>
             <many-to-many class="com.feelergo.ORM.Member" column="member_id"/>
            </set> 
        </class>
    </hibernate-mapping>
      

  7.   

    这个...我刚才试验了一下
    mFeed.add(3); 
    mem.setFeed(mFeed);经过也不行 看来我其他地方也有问题着呢