我正在尝试与JPA进行一些聊天。除了一件事,每件事都有效。我想,当我的用户打开与endPoint的连接时,保存他的房间号,他的昵称和timstamp。 我的表已经很好地创建了列,但是我无法在DataBase中保留我的Connexion对象。
我正在使用Glasfish 4.0,我已经创建了运行良好的JDBCRessources和JDBC Connection池。
这是我的ChatEndPoint.Java
package server;
import java.io.IOException;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/websocket/{room-name}/{nick-name}", encoders = { ChatMessageEncoder.class }, decoders = { ChatMessageDecoder.class })
public class ChatEndPoint {
// traitement de la connexion d'un client
@OnOpen
public void open(Session session, EndpointConfig conf, @PathParam("room-name") String roomName, @PathParam("nick-name") String nickName) throws Exception {
System.out.println("connection ouverte");
session.getUserProperties().put("salle", roomName);
DAO dao=new DAO();
dao.createConnection(nickName, roomName);
}
// traitement de la reception d'un message client
@OnMessage
public void onMessage(Session session, ChatMessage msg) throws IOException,
EncodeException {
if (msg instanceof ChatMessage) {
ChatMessage reponse = new ChatMessage(msg.getEmetteur(),
msg.getSalle(), msg.getMessage());
for (Session sess : session.getOpenSessions()) {
if (sess.isOpen()
&& sess.getUserProperties().get("salle")
.equals(msg.getSalle()))
sess.getBasicRemote().sendObject(reponse);
}
}
}
}
我的Connexion课程代表我要保存的实体:
Connexion.java
package server;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class Connexion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column( name = "nickName" )
protected String nickName;
@NotNull
@Column( name = "roomName" )
protected String roomName;
@Column( name = "dateConnexion" )
protected Timestamp connectionDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
public Timestamp getConnectionDate() {
return connectionDate;
}
public void setConnectionDate(Timestamp timestamp) {
this.connectionDate = timestamp;
}
}
DAO.java
package server;
import java.sql.Timestamp;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
@Stateless
@LocalBean
public class DAO {
@PersistenceUnit
private EntityManagerFactory emf;
// Injection du manager, qui s'occupe de la connexion avec la BDD
@PersistenceContext(unitName="projetwebee1")
EntityManager em;
// Enregistrement d'un nouvel utilisateur
public void createConnection(String nickName, String roomName) throws Exception{
this.emf=Persistence.createEntityManagerFactory("projetwebee1");
this.em = this.emf.createEntityManager();
Connexion c = new Connexion();
c.setNickName(nickName);
c.setRoomName(roomName);
c.setConnectionDate(new Timestamp((new java.util.Date()).getTime()));
System.out.println(" "+em);
em.persist(c);
System.out.println("persist OK");
}
}
JPA生成的persistence.xml。但我编辑了部分内容
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="projetwebee1" transaction-type="JTA">
<jta-data-source>JEEProjectJNDIFinal3</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>
所以在我试图坚持我的实体后,我无法在我的数据资源管理器中看到它。我已经尝试了很多其他方法,而不是我在官方文档上发现的,甚至在这里。但没有人成功。
感谢您的帮助
答案 0 :(得分:1)
EJB容器在您的bean中注入实体管理器,但您丢弃它并将其替换为您自己创建的实体管理器。你所需要的只是
@Stateless
@LocalBean
public class DAO {
@PersistenceContext
EntityManager em;
public void createConnection(String nickName, String roomName) {
Connexion c = new Connexion();
c.setNickName(nickName);
c.setRoomName(roomName);
c.setConnectionDate(new Timestamp((new java.util.Date()).getTime()));
em.persist(c);
}
但问题是,不是让容器创建这个EJB,而是自己实现它,将应该是可注入的事务EJB转换为dumb对象,而不受EJB容器的管理。永远不要使用new来获取EJB的实例。使用依赖注入。
而不是
@ServerEndpoint(value = "/websocket/{room-name}/{nick-name}", encoders = { ChatMessageEncoder.class }, decoders = { ChatMessageDecoder.class })
public class ChatEndPoint {
// traitement de la connexion d'un client
@OnOpen
public void open(Session session, EndpointConfig conf, @PathParam("room-name") String roomName, @PathParam("nick-name") String nickName) throws Exception {
System.out.println("connection ouverte");
session.getUserProperties().put("salle", roomName);
DAO dao=new DAO();
dao.createConnection(nickName, roomName);
使用
@ServerEndpoint(value = "/websocket/{room-name}/{nick-name}", encoders = { ChatMessageEncoder.class }, decoders = { ChatMessageDecoder.class })
public class ChatEndPoint {
@Inject
private DAO dao;
// traitement de la connexion d'un client
@OnOpen
public void open(Session session, EndpointConfig conf, @PathParam("room-name") String roomName, @PathParam("nick-name") String nickName) throws Exception {
System.out.println("connection ouverte");
session.getUserProperties().put("salle", roomName);
dao.createConnection(nickName, roomName);