1

我正在使用 Java 中的 Google App Engine 和 JDO 为移动应用程序开发服务器端,但同时访问数据库时遇到了一些问题。

我正在做的应用程序是聊天,当两个人同时访问数据库时,其中一条消息丢失了。我认为这是因为这两种访问中的一种是在另一种之前完成的,即在它保存在数据库中之前,这就是其中一条消息丢失的原因。

你知道一些解决方案吗?诸如获取对数据库中相同注册表的访问权并将它们放入队列或堆栈中以供最近访问之类的东西。

提前致谢!

这是我的代码:

对话.java:

import java.util.LinkedList;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)  
public class Conversation 
{
    @PrimaryKey  
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)  
    private Long id;

    @Persistent
    private Long idUser;

    @Persistent(mappedBy = "conversation")
    private LinkedList<Message> messages;

    public Conversation(Long idUser) 
    {
        this.idUser = idUser;

        messages = new LinkedList<Message>();       
    }

    public Long getId() {
        return id;
    }

    public Long getIdUser() {
        return idUser;
    }

    public LinkedList<Message> getMessages() {
        return messages;
    }
}

消息.java:

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;

@PersistenceCapable(identityType = IdentityType.APPLICATION)  
public class Message 
{
    @PrimaryKey  
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)  
    private Key id;

    @Persistent
    private Conversation conversation;

    @Persistent
    private String text;

    @Persistent
    private String hour;

    public Message(String text, String hour)
    {
        this.text = text;
        this.hour = hour;
    }

    public String getText() 
    {
        return text;
    }

    public String getHour() 
    {
        return hour;
    }

    public Key getId() 
    {
        return id;
    }

    public Conversation getConversation() {
        return conversation;
    }
}

保存消息:

final PersistenceManager persistenceManager = PMF.get().getPersistenceManager();      

String strQuery = "select from " + Conversation.class.getName() + " where id == " + id;
persistenceManager.getFetchPlan().setGroup(FetchGroup.ALL);
final Query query = persistenceManager.newQuery(strQuery);

try 
{
    List<Conversation> conversations = (List<Conversation>) query.execute;

    Conversation detached = null;
    detached = persistenceManager.detachCopy(conversations.get(0));

    detached.getMessages().add(message);
    persistenceManager.makePersistent(detached);
} finally {
    persistenceManager.close();
}
4

0 回答 0