I'm trying to implement a little chat with JPA. Everythings work except one thing. I want, when my user open the connection with the endPoint, save his room number, his nickname and the timstamp.
My table has been well created, columns too but i cant persist my Connexion Object in DataBase.
I'm using Glasfish 4.0 and i've already create my JDBCRessources and JDBC Connection pools who are worked well.
Here my 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);
}
}
}
}
My Connexion class who represent my entity to save :
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");
}
}
persistence.xml generated by JPA. But i edited some part of it
<?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>
So after i'm trying to persist my entity i cant see it in my data Explorer. I've already try a lot of other method than i found on the official doc or even here. But no one succeed.
Thanks for your help
The EJB container injects an entity manager in your bean, but you discard it and replace it by one you create yourself. All you need is
#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);
}
But the problem is that instead of letting the container create this EJB, you instanciate it by yourself, transforming what should be an injectable, transactional EJB into a dumb object, unmanaged by the EJB container. NEVER use new to get an instance of an EJB. Use dependency injection.
Instead of
#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);
use
#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);
Related
Iam trying to build a sample application with JAXRS/Hibernate.
I have sample data in my database,but i could not retrieve it.Please verify my code and let me know where Iam making error.
Entity class
package org.cricket.cricketstats.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Table(name="player_info")
#Entity
public class PlayerInfo {
#Id
#Column(name="player_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long playerId;
#Column(name="player_name")
private String playerName;
#Column(name="player_role")
private String playerRole;
#Column(name="player_batting_style")
private String playerBattingStyle;
#Column(name="player_bowling_style")
private String playerBowlingStyle;
#Column(name="player_image")
private String playerImage;
#Column(name="player_profile_desc")
private String playerProfile;
public PlayerInfo(){
}
public PlayerInfo(long playerId, String playerName, String playerRole, String playerBattingStyle,
String playerBowlingStyle, String playerImage, String playerProfile) {
super();
this.playerId = playerId;
this.playerName = playerName;
this.playerRole = playerRole;
this.playerBattingStyle = playerBattingStyle;
this.playerBowlingStyle = playerBowlingStyle;
this.playerImage = playerImage;
this.playerProfile = playerProfile;
}
public long getPlayerId() {
return playerId;
}
public void setPlayerId(long playerId) {
this.playerId = playerId;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerRole() {
return playerRole;
}
public void setPlayerRole(String playerRole) {
this.playerRole = playerRole;
}
public String getPlayerBattingStyle() {
return playerBattingStyle;
}
public void setPlayerBattingStyle(String playerBattingStyle) {
this.playerBattingStyle = playerBattingStyle;
}
public String getPlayerBowlingStyle() {
return playerBowlingStyle;
}
public void setPlayerBowlingStyle(String playerBowlingStyle) {
this.playerBowlingStyle = playerBowlingStyle;
}
public String getPlayerImage() {
return playerImage;
}
public void setPlayerImage(String playerImage) {
this.playerImage = playerImage;
}
public String getPlayerProfile() {
return playerProfile;
}
public void setPlayerProfile(String playerProfile) {
this.playerProfile = playerProfile;
}
}
Rest Resource
package org.cricket.cricketstats.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cricket.cricketstats.data.PlayerInfoDAO;
import org.cricket.cricketstats.model.PlayerInfoBean;
#Path("players")
public class CricketResources {
PlayerInfoBean playerInfoBean= new PlayerInfoBean();
#GET
#Path("{playerId}")
#Produces(MediaType.APPLICATION_JSON)
public PlayerInfoBean getPlayerDetails(#PathParam("playerId") long id) {
PlayerInfoDAO dao= new PlayerInfoDAO();
dao.getPlayerInfo();
playerInfoBean.setPlayerId(id);
return playerInfoBean;
}
}
Config file
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connection settings -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/cricket</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">postgres</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Print executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- validate all database on startup -->
<property name="hibernate.hbm2ddl.auto">validate</property>
<!-- Annotated entity classes -->
<mapping class="org.cricket.cricketstats.data.PlayerInfo"/>
</session-factory>
</hibernate-configuration>
DAO class
package org.cricket.cricketstats.data;
import java.util.List;
import org.cricket.cricketstats.model.PlayerInfoBean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class PlayerInfoDAO {
public void getPlayerInfo(){
Configuration config=new Configuration().configure();
ServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
// SessionFactory factory = config.buildSessionFactory(builder.build());
SessionFactory factory = config.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Transaction tx =session.beginTransaction();
List infoList=session.createQuery("FROM PlayerInfo").list();
tx.commit();
session.close();
System.out.println(infoList.get(0).getPlayerName());
}
}
**I have tried to give full path also in query **
The way is used by you to building a session factory is not correct for Hibernate 5. It can be used only for Hibernate 4.
Use this instead
SessionFactory factory = new Configuration().configure().buildSessionFactory();
I'm trying to configure an example JPA application in Eclipse, and deploy it to TomEE+. The datasource is container managed. I keep seeing the following error when attempting to create the EntityManager:
The persistence provider is attempting to use properties in the persistence.xml file to resolve the data source. A Java Database Connectivity (JDBC) driver or data source class name must be specified in the openjpa.ConnectionDriverName or javax.persistence.jdbc.driver property. The following properties are available in the configuration: "org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#414793b4".
Any idea what is wrong with this configuration?
Below is the code.
tomee.xml
<tomee>
<Resource id="jdbc/MyAppDS" type="DataSource">
JdbcDriver com.microsoft.sqlserver.jdbc.SQLServerDriver
JdbcUrl jdbc:sqlserver://localhost:1433/db_dev
UserName user
Password password
JtaManaged true
DefaultAutoCommit false
</Resource>
</tomee>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0">
<persistence-unit name="Simplest" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>jdbc/MyAppDS</jta-data-source>
<class>social.Media</class>
</persistence-unit>
</persistence>
Media.java
package social;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "media")
public class Media {
#Id
#Column(name = "id")
private String id;
private String description;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Controller.java
package social;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Controller {
#Inject private Media media;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Simplest");
EntityManager em = emf.createEntityManager(); // exception reported on this line
.
.
.
return media.getDescription();
}
}
You are using JTA-managed Entity Manager Factory, I think that instead of manual creation of EntityManagerFactory you should let application server do it for you, like this in controller:
#Path("/hello")
public class Controller {
#PersistenceContext(unitName="Simplest")
private EntityManager em;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
// get Media from database - replace with your own code
Media media = em.find(Media.class, "1");
return media.getDescription();
}
}
I am using EJB 3.0 and Hibernate 4 with PostgreSQL as my database server to create a multitenant system where each tenant will have separate but identical schema. I am still in the trial stage where I have 3 schemes public, company1, company2 all having a single table person. Now what i want to do is change the schema in runtime as per the user so that he can view the data of his/her company only.
Here is my sample code:
Entity Object:
package com.neebal.domain;
import java.io.Serializable;
import java.lang.Long;
import java.lang.String;
import javax.persistence.*;
import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.annotations.MultitenantType;
#Entity
//#Table(schema = "company1")
public class Person implements Serializable {
#Id
private Long id;
private String name;
private static final long serialVersionUID = 1L;
public Person() {
super();
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The MultiTenantConnectionProvider class:
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
public class MultiTenantProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService {
private static final long serialVersionUID = 4368575201221677384L;
private C3P0ConnectionProvider connectionProvider = null;
#Override
public boolean supportsAggressiveRelease() {
return false;
}
#Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
connectionProvider = new C3P0ConnectionProvider();
connectionProvider.injectServices(serviceRegistry);
connectionProvider.configure(lSettings);
}
#Override
public boolean isUnwrappableAs(Class clazz) {
return false;
}
#Override
public <T> T unwrap(Class<T> clazz) {
return null;
}
#Override
public Connection getAnyConnection() throws SQLException {
final Connection connection = connectionProvider.getConnection();
return connection;
}
#Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e);
}
return connection;
}
#Override
public void releaseAnyConnection(Connection connection) throws SQLException {
try {
connection.createStatement().execute("SET SCHEMA 'public'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [public]", e);
}
connectionProvider.closeConnection(connection);
}
#Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
}
The CurrentTenantIdentifierResolver class:
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
public class SchemaResolver implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
System.out.println("company1");
return "company1"; //TODO: Implement service to identify tenant like: userService.getCurrentlyAuthUser().getTenantId();
}
#Override
public boolean validateExistingCurrentSessions() {
return false;
}
}
The persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testEJB">
<jta-data-source>jdbc/testpgsql</jta-data-source>
<properties>
<property name="javax.persistence.provider" value="org.hibernate.ejb.HibernatePersistence" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/test" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.multiTenancy" value="SCHEMA" />
<property name="hibernate.tenant_identifier_resolver" value="com.neebal.util.multitenancy.SchemaResolver" />
<property name="hibernate.multi_tenant_connection_provider"
value="com.neebal.util.multitenancy.MultiTenantProvider" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>
And finally the DAO class:
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.neebal.domain.Person;
/**
* Session Bean implementation class PersonDAO
*/
#Stateless
public class PersonDAO implements PersonDAOLocal {
#PersistenceContext
EntityManager entityManager;
/**
* Default constructor.
*/
public PersonDAO() {
// TODO Auto-generated constructor stub
}
#Override
public void save(Person person) {
entityManager.persist(person);
}
#Override
public List<Person> getAll() {
Person person = entityManager.find(Person.class, 2L);
System.out.println(person.getName());
return null;
}
}
In this example I have hardcoded the schema as company1 but it still persists or retrieves the data from public schema. So where am I wrong in this example.
The question is already 1 year old, but I think the problem of using different schemas depending on some runtime condition is common one, so I'll answer anyway. If I understand you right and the set of tenants is small, then I think the easiest way to do what you're trying to achieve is to define a separate persistence units for each tenant in your persistence.xml
<persistence-unit name="public">
.. settings for first schema
</persistence-unit>
<persistence-unit name="company1">
.. settings for first schema
</persistence-unit>
<persistence-unit name="company2">
.. settings for first schema
</persistence-unit>
Then have for each one a separate entityManager:
#PersistenceContext(unitName = "public")
private EntityManager emPublic;
#PersistenceContext(unitName = "company1")
private EntityManager emComp1;
#PersistenceContext(unitName = "company2")
private EntityManager emComp1;
Now you can switch between entity managers, given the currently authorized user.
Depending on your exact infrastructure etc, there may be other approaches, too. For instance, if all your schemas are on the same server, then you could also try to pass the schema names directly to your queries.
This is pure JPA and thus portable and not depending on any persistence provider like hibernate nor on your DBMS.
I am using Java,Maven,Hibernate 3/JPA ,Eclipse to implement a PUT method for populating a Mysql db.
Here is my POJO
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "Person", catalog = "mydb", uniqueConstraints = {
#UniqueConstraint(columnNames = "Person"),})
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String Name;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", unique = true, nullable = false, length = 30)
public String getName() {
return flowName;
}
public void setName(String Name) {
this.Name = Name;
}
}
Here is my annotations class.
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.google.gson.Gson;
import com.tracker.domain.Flow;
import com.tracker.persistence.HibernateUtil;
public class PersonService {
private Logger LOG = Logger.getLogger(TrackerService.class);
String JsonString = "{\"name\":\"John Doe\"}";
Gson gson = new Gson();
Person person = gson.fromJson(JsonString,Person.class);
#PUT
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void processandSaveJson(Person person) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String Name = Person.getName();
person.setName(Name);
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
}
}
Here is my Hibernate.Util.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Here is my SessionFactory Context Listener class
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.Logger;
import org.hibernate.Session;
#WebListener
public class SessionFactoryListener implements ServletContextListener {
private Logger LOG = Logger.getLogger(SessionFactoryListener.class);
#Override
public void contextInitialized(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextInitialized()---\n");
}
Session session = HibernateUtil.getSessionFactory().openSession();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextDestroyed()\n");
}
HibernateUtil.shutdown();
}
}
When I try to run this using Tomcat Server, i get the following error.
type Status report
message Method Not Allowed
description The specified HTTP method is not allowed for the requested resource.
I am very new to this. Kindly let me know what I am doing wrong. I trying to insert a
record into a mysql db using the above values. Kindly help me out.
Thanks,
Jack
as mentioned in the comments, you should supply your calling code along with the rest. but since you already mentioned that you're using a browser to make the request, it should be mentioned that most/no browsers support 'put' without using javadcript. what you are doing looks like a simple 'get'.
so the solution is to either use javascript in your form submission, or discard REST and have Urls that reflect the method (eg. /person/new/ and /person/{personId}
I am using Jboss7.1 and jpa , ejb
I want to insert data -with OneToMany relationship- into my mysql database.
I have two entitys personne and voiture. I want to save a person in my database and associate voiture for him. The problem is that when i test my code (test), i find that there is a new personne added to my database and there is no voiture added in the table voiture
please can you help me .
code :
the entity personne
package com.domain;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Set;
/**
* The persistent class for the personne database table.
*
*/
#Entity
public class Personne implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int idpersonne;
private String nom;
//bi-directional many-to-one association to Voiture
#OneToMany(mappedBy="personne")
private Set<Voiture> voitures;
public Personne() {
}
public Personne(String nom) {
super();
this.nom = nom;
}
public int getIdpersonne() {
return this.idpersonne;
}
public void setIdpersonne(int idpersonne) {
this.idpersonne = idpersonne;
}
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Set<Voiture> getVoitures() {
return this.voitures;
}
public void setVoitures(Set<Voiture> voitures) {
this.voitures = voitures;
}
}
entity voiture
package com.domain;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the voiture database table.
*
*/
#Entity
public class Voiture implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int idvoiture;
private String type;
//bi-directional many-to-one association to Personne
#ManyToOne
private Personne personne;
public Voiture() {
}
public Voiture(String type) {
super();
this.type = type;
}
public int getIdvoiture() {
return this.idvoiture;
}
public void setIdvoiture(int idvoiture) {
this.idvoiture = idvoiture;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public Personne getPersonne() {
return this.personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
}
this is the interface
package com.DAO;
import javax.ejb.Remote;
import com.domain.Personne;
#Remote
public interface PersonneDAO {
public void save(Personne personne);
public String sayhello();
}
the implementation
package com.DAO.Impl;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.DAO.VoitureDAO;
import com.domain.Voiture;
#Stateless
public class VoitureDAOImpl implements VoitureDAO {
#PersistenceContext(name = "JPADD")
EntityManager em;
#Override
public void save(Voiture voiture) {
em.persist(voiture);
}
}
the implementation
package com.DAO.Impl;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.DAO.PersonneDAO;
import com.domain.Personne;
#Stateless
public class PersonneDAOImpl implements PersonneDAO {
#PersistenceContext(name = "JPADD")
EntityManager em;
#Override
public String sayhello() {
// TODO Auto-generated method stub
return "helllllllllllllllllo";
}
#Override
public void save(Personne personne) {
em.persist(personne);
}
}
this is the test
package test;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.DAO.PersonneDAO;
import com.domain.Personne;
import com.domain.Voiture;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Context intialcontext;
Properties properties = new Properties();
properties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
try {
intialcontext = new InitialContext(properties);
PersonneDAO dao = (PersonneDAO) intialcontext
.lookup("ejb:/projetweb/PersonneDAOImpl!com.DAO.PersonneDAO");
// /----------------------------objet voiture-------------
Voiture voiture = new Voiture("216");
Set<Voiture> voitures = new HashSet<Voiture>();
voitures.add(voiture);
// -------------------------------------------------------
Personne personne = new Personne("slatnia");
personne.setVoitures(voitures);
dao.save(personne);
} catch (NamingException e) {
e.printStackTrace();
}
}
}
and this is my jboss-ejb-client.properties
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
Try add following attributes to the #OneToMany annotation
#OneToMany(cascade=CascadeType.ALL)
You should add cascade = CascadeType.PERSIST in the #OneToMany
CascadeType.PERSIST
When persisting an entity, also persist the entities held in this
field. We suggest liberal application of this cascade rule, because if
the EntityManager finds a field that references a new entity during
flush, and the field does not use CascadeType.PERSIST, it is an error.
example:
#OneToMany(cascade = CascadeType.PERSIST)
private Set<Voiture> voitures;
Javadoc for CascadeType and other doc at here.