Search Results

Search found 1098 results on 44 pages for 'persistence'.

Page 12/44 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Is it possible to implement a lightweight database using Blackberry Persistance options?

    - by Tobias
    First I would like to explain why I want to use alternate Blackberry Persistance options rather than a Blackberry database itself, say SQLite. The reason is that the application i'm designing, I want it to be used in all the previous versions of Blackberry rather than just the ones having OS 5.0 or greater. Now, coming back to the actual question, I have got a database that I want to replicate to be used in the Blackberry application. The database has 8 tables and each table has approximately 12 different columns. One of the table has 1000 rows. Now if I was to implement this DB for a Blackberry application , keeping in mind that it will work on all the versions of Blackberry, what would be the best way to implement it?

    Read the article

  • Hibernate entities: columns without entity properties

    - by lewap
    Is there a way to "magically" persist a column which is not represented as a property in an entity? Concretely I want to add audit info to an entity without having the audit info on the entity. The audit values are not stored in the entity, but are retrieved from the environment at the time of persisting the entity. This happens in a AuditInfoUserType. The nullSafeSet gets the info from the SecurityContext, instead of reading from the entity. In the hibernate mapping, however, the audit info properties have to be defined. Is there a way in hibernate to define columns without properties?

    Read the article

  • Get location from where the Java code is executed

    - by drasto
    I have a swing Java application that preserves a lot of data (you can think of a game and its saves for example). Those data are stored in files rather then in database. I would like to keep this files near installation files(.jar file) of my application.Some users(like me) are used to delete default application folder of OS when it comes to large and I don't want them to loose their data this way. Any ideas how to do this easily ? How do I get the folder of the .jar file from program that is executing form that .jar file? Or how do I output files directly into some package? How do I create packages(folders inside jar) dynamically ? Or is there a simple way to distribute Java application in other formats then .jar and then store generated data in installation (sub)folder ? Thanks for reading

    Read the article

  • Persistent Objects in ASP.NET

    - by user204588
    Hello, I'm trying to find the best way to persist an object or in use the same object at a later point in the code. So, I create an object, then you're redirected to another page(a form) that needs to use variables from that object. That form is submitted to a third party and there is stuff done on their end and then they request a page on my application that runs some more code and needs the objects variables again. I thought about Database but this is all done at once. This is done during a user checkout process and after it's over, there's no reason to retrieve this object again. So adding and retrieving from a database seems like it would be overkill and I think it would make the process slower. Right now I'm using Session but I keep hearing not to use that but no one is really saying why I shouldn't except it is bad practice. I can't really use post back values because the pages don't work that way. The checkout process starts off in a dll code that redirects to the form that is submitted to the third party and the a page is requested by the third party. So, I'm not really sure of the best way. What are all the options and what does everyone recommend as the best way?

    Read the article

  • Best practice: How to persist simple data without a database in django?

    - by Infinity
    I'm building a website that doesn't require a database because a REST API "is the database". (Except you don't want to be putting site-specific things in there, since the API is used by mostly mobile clients) However there's a few things that normally would be put in a database, for example the "jobs" page. You have master list view, and the detail views for each job, and it should be easy to add new job entries. (not necessarily via a CMS, but that would be awesome) e.g. example.com/careers/ and example.com/careers/77/ I could just hardcode this stuff in templates, but that's no DRY- you have to update the master template and the detail template every time. What do you guys think? Maybe a YAML file? Or any better ideas? Thx

    Read the article

  • Recommand a Perl module to persist a large object for re-use between runs?

    - by Alnitak
    I've got a large XML file, which takes 40+ seconds to parse with XML::Simple. I'd like to be able to cache the resulting parsed object so that on the next run I can just retrieve the parsed object and not reparse the whole file. I've looked at using Data::Dumper but the documentation is a bit lacking on how to store and retrieve its output from disk files. Other classes I've looked at (e.g. Cache::Cache) appear designed for storage of many small objects, not a single large one. Can anyone recommend a module designed for this?

    Read the article

  • Automatically Persisting a Complex Java Object

    - by VeeArr
    For a project I am working on, I need to persist a number of POJOs to a database. The POJOs class definitions are sometimes highly nested, but they should flatten okay, as the nesting is tree-like and contains no cycles (and the base elements are eventually primitives/Strings). It is preferred that the solution used create one table per data type and that the tables will have one field per primitive member in the POJO. Subclassing and similar problems are not issues for this particular project. Does anybody know of any existing solutions that can: Automatically generate a CREATE TABLE definition from the class definition Automatically generate a query to persist an object to the database, given an instance of the object Automatically generate a query to retrieve an object from the database and return it as a POJO, given a key. Solutions that can do this with minimum modifications/annotions to the class files and minimum external configuration are preferred. Example: Java classes //Class to be persisted class TypeA { String guid; long timestamp; TypeB data1; TypeC data2; } class TypeB { int id; int someData; } class TypeC { int id; int otherData; } Could map to CREATE TABLE TypeA ( guid CHAR(255), timestamp BIGINT, data1_id INT, data1_someData INT, data2_id INt, data2_otherData INT ); Or something similar.

    Read the article

  • Hibernate OneToMany and ManyToOne confusion! Null List!

    - by squizz
    I have two tables... For example - Company and Employee (let's keep this real simple) Company( id, name ); Employee( id, company_id ); Employee.company_id is a foreign key. My entity model looks like this... Employee @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "company_id") Company company; Company @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "company_id") List<Employee> employeeList = new ArrayList<Employee>(); So, yeah I want a list of employees for a company. When I do the following... Employee e = new Employee(); e.setCompany(c); //c is an Company that is already in the database. DAO.insertEmployee(e); //this works fine! If I then get my Company object it's list is empty! Ive tried endless different ways from the Hibernate documentation! Obviously not tried the correct one yet! I just want the list to be populated for me or find out a sensible alternative. Help would be greatly appreciated, thanks!

    Read the article

  • What data (if any) persists across web-requests in Ruby on Rails?

    - by Daniel Beardsley
    I decided to use the singleton design pattern while creating a view helper class. This got me thinking; will the singleton instance survive across requests? This led to another question, Which variables (if any) survive across web requests and does that change depending on deployment? (Fastcgi, Mongrel, Passenger, ...) I know that Controller instance variables aren't persisted. I know Constants are persisted (or reloaded?). But I don't know about class variables, instance variables on a class, Eigenclasses, ...

    Read the article

  • Alternatives to persisting objects than using __destruct() in PHP

    - by Michael
    I usually use a classes destructor method __destruct() to persist objects to session or what have you. It is just very convinient, but I'm curious to if there are any other methods that are equally appealing. Do you know of such? The curiousity arose as I was to merge/utilize two frameworks that both made use of __destruct() for persistance resulting in a race-problem.

    Read the article

  • MyEntity.findAllByNameNotLike('bad%')

    - by Richard Paul
    I'm attempting to pull up all entities that have a name that doesn't partially match a given string. MyEntity.findAllByNameNotLike('bad%') This gives me the following error: No such property: nameNot for class: MyEntity Possible solutions: name" type="groovy.lang.MissingPropertyException" I had a quick look at the criteria style but I can't seem to get that going either, def results = MyEntity.withCritieria { not(like('name', 'bad%')) } No signature of method: MyEntity.withCritieria() is applicable for argument types: (MyService$_doSomething_closure1) Ideally I would like to be able to apply this restriction at the finder level as the database contains a large number of entities that I don't want to load up and then exclude for performance reasons. [grails 1.3.1]

    Read the article

  • Java JPA Hibernate Spring @EntityListeners throws org.springframework.dao.DataIntegrityViolationException

    - by user
    I am using Spring 3 with Hibernate 3. I would like to update the last modification date automatically when an entity is updated. Below is the sample code: HibernateConfig: @Configuration public class HibernateConfig { @Bean public DataSource dataSource() throws Exception { DriverManagerDataSource dataSource = new DriverManagerDataSource(); Properties properties = new Properties(); properties.load(ClassLoader.getSystemResourceAsStream(new String("hibernate.properties"))); dataSource.setUrl(properties.getProperty(new String("jdbc.url"))); dataSource.setUsername(properties.getProperty(new String("jdbc.username"))); dataSource.setPassword(properties.getProperty(new String("jdbc.password"))); dataSource.setDriverClassName(properties.getProperty(new String("jdbc.driverClassName"))); return dataSource; } @Bean public AnnotationSessionFactoryBean sessionFactory() throws Exception { AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean(); Properties hibernateProperties = new Properties(); Properties properties = new Properties(); properties.load(ClassLoader.getSystemResourceAsStream(new String("hibernate.properties"))); // set the Hibernate Properties hibernateProperties.setProperty(new String("hibernate.dialect"), properties.getProperty(new String("hibernate.dialect"))); hibernateProperties.setProperty(new String("hibernate.show_sql"), properties.getProperty(new String("hibernate.show_sql"))); hibernateProperties.setProperty(new String("hibernate.hbm2ddl.auto"), properties.getProperty(new String("hibernate.hbm2ddl.auto"))); sessionFactory.setDataSource(dataSource()); sessionFactory.setHibernateProperties(hibernateProperties); sessionFactory.setAnnotatedClasses(new Class[]{Message.class}) return sessionFactory; } @Bean public HibernateTemplate hibernateTemplate() throws Exception { HibernateTemplate hibernateTemplate = new HibernateTemplate(); hibernateTemplate.setSessionFactory(sessionFactory().getObject()); return hibernateTemplate; } } DAOConfig: @Configuration public class DAOConfig { @Autowired private HibernateConfig hibernateConfig; @Bean public MessageDAO messageDAO() throws Exception { MessageDAO messageDAO = new MessageHibernateDAO(hibernateConfig.hibernateTemplate()); return messageDAO; } } Message: import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity @Table @EntityListeners(value = MessageListener.class) public class Message implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column private int id; @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date lastMod; public Message() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getLastMod() { return lastMod; } public void setLastMod(Date lastMod) { this.lastMod = lastMod; } } MessageListener: import java.util.Date; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import org.springframework.stereotype.Component; @Component public class MessageListener { @PrePersist @PreUpdate public void setLastMod(Message message) { message.setLastMod(new Date()); } } When running this the MessageListener is not being invoked. I use a DAO design pattern and when calling dao.update(Message) it throws the following Exception: org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value: com.persistence.entities.MessageStatus.lastMod; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com.persistence.entities.Message.lastMod at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:665) at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) at com.persistence.dao.hibernate.GenericHibernateDAO.save(GenericHibernateDAO.java:38) Having looked at a number of websites there seems not to be a solution.

    Read the article

  • how openjpa2.0 enhances entities at runtime?

    - by Digambar Daund
    Below is my test code: package jee.jpa2; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @Test public class Tester { EntityManager em; EntityTransaction tx; EntityManagerFactory emf; @BeforeClass public void setup() { emf = Persistence.createEntityManagerFactory("basicPU", System.getProperties()); } @Test public void insert() { Item item = new Item(); for (int i = 0; i < 1000; ++i) { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); item.setId(null); em.persist(item); tx.commit(); em.clear(); em.close(); tx=null; em=null; } } @Test public void read() { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query findAll = em.createNamedQuery("findAll"); List<Item> all = findAll.getResultList(); for (Item item : all) { System.out.println(item); } tx.commit(); } } And here is the entity: package jee.jpa2; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity @NamedQuery(name="findAll", query="SELECT i FROM Item i") public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", nullable = false, updatable= false) protected Long id; protected String name; public Item() { name = "Digambar"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return String.format("Item [id=%s, name=%s]", id, name); } } After executing test I get Error: Item [id=1, name=Digambar] Item [id=2, name=Digambar] PASSED: read FAILED: insert <openjpa-2.0.0-r422266:935683 nonfatal store error> org.apache.openjpa.persistence.EntityExistsException: Attempt to persist detached object "jee.jpa2.Item-2". If this is a new instance, make sure any version and/or auto-generated primary key fields are null/default when persisting. FailedObject: jee.jpa2.Item-2 at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2563) at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2423) at org.apache.openjpa.kernel.DelegatingBroker.persist(DelegatingBroker.java:1069) at org.apache.openjpa.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:705) at jee.jpa2.Tester.insert(Tester.java:33) Please Explain whats happening here?

    Read the article

  • Why does Hibernate ignore the JPA2 standardized properties in my persistence.xml?

    - by Ophidian
    I have an extremely simple web application running in Tomcat using Spring 3.0.1, Hibernate 3.5.1, JPA 2, and Derby. I am defining all of my database connectivity in persistence.xml and merely using Spring for dependency injection. I am using embedded Derby as my database. Everything works correctly when I define the driver and url properties in persistence.xml in the classic Hibernate manner as thus: <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver"/> <property name="hibernate.connection.url" value="jdbc:derby:webdb;create=true"/> The problems occur when I switch my configuration to the JPA2 standardized properties as thus: <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/> <property name="javax.persistence.jdbc.url" value="jdbc:derby:webdb;create=true"/> When using the JPA2 property keys, the application bails hard with the following exception: java.lang.UnsupportedOperationException: The user must supply a JDBC connection Does anyone know why this is failing? NOTE: I have copied the javax... property strings straight from the Hibernate reference documentation, so a typo is extremely unlikely.

    Read the article

  • I'm running Ubuntu notebook on a USB drive with 1GB persistence. Where are my XAMPP files?

    - by CDeanMartin
    I just began running Ubuntu Notebook on my 2GB USB stick, with 1GB persistence. After I installed XAMPP, I rebooted to make sure the persistence was working. It worked! My XAMPP installation worked, and it comes up when I type localhost into the browser. The sample apps work, including the ones using MySQL. But I can't find the application files! I am used to the vast labyrinth of files in Windows Explorer, and looking through 'Files and Folders' in GNOME, there seem to only be 7 or 8 folders in the entire OS? What is really going on here? I looked through them all and where is XAMPP? When I code PHP with a WAMP stack, all the .php files go in the 'WWW folder' What is the Linux equivalent of the WWW folder?

    Read the article

  • Using Oracle Proxy Authentication with JPA (eclipselink-Style)

    - by olaf.heimburger
    Security is a very intriguing topic. You will find it everywhere and you need to implement it everywhere. Yes, you need. Unfortunately, one can easily forget it while implementing the last mile. The Last Mile In a multi-tier application it is a common practice to use connection pools between the business layer and the database layer. Connection pools are quite useful to speed database connection creation and to split the load. Another very common practice is to use a specific, often called technical, user to connect to the database. This user has authentication and authorization rules that apply to all application users. Imagine you've put every effort to define roles for different types of users that use your application. These roles are necessary to differentiate between normal users, premium users, and administrators (I bet you will find or already have more roles in your application). While these user roles are pretty well used within your application, once the flow of execution enters the database everything is gone. Each and every user just has one role and is the same database user. Issues? What Issues? As long as things go well, this is not a real issue. However, things do not go well all the time. Once your application becomes famous performance decreases in certain situations or, more importantly, current and upcoming regulations and laws require that your application must be able to apply different security measures on a per user role basis at every stage of your application. If you only have a bunch of users with the same name and role you are not able to find the application usage profile that causes the performance issue, or which user has accessed data that he/she is not allowed to. Another thread to your role concept is that databases tend to be used by different applications and tools. These tools can be developer tools like SQL*Plus, SQL Developer, etc. or end user applications like BI Publisher, Oracle Forms and so on. These tools have no idea of your applications role concept and access the database the way they think is appropriate. A big oversight for your perfect role model and a big nightmare for your Chief Security Officer. Speaking of the CSO, brings up another issue: Password management. Once your technical user account is compromised, every user is able to do things that he/she is not expected to do from the design of your application. Counter Measures In the Oracle world a common counter measure is to use Virtual Private Database (VPD). This restricts the values a database user can see to the allowed minimum. However, it doesn't help in regard of a connection pool user, because this one is still not the real user. Oracle Proxy Authentication Another feature of the Oracle database is Proxy Authentication. First introduced with version 9i it is a quite useful feature for nearly every situation. The main idea behind Proxy Authentication is, to create a crippled database user who has only connect rights. Even if this user is compromised the risks are well understood and fairly limited. This user can be used in every situation in which you need to connect to the database, no matter which tool or application (see above) you use.The proxy user is perfect for multi-tier connection pools. CREATE USER app_user IDENTIFIED BY abcd1234; GRANT CREATE SESSION TO app_user; But what if you need to access real data? Well, this is the primary use case, isn't it? Now is the time to bring the application's role concept into play. You define database roles that define the grants for your identified user groups. Once you have these groups you grant access through the proxy user with the application role to the specific user. CREATE ROLE app_role_a; GRANT app_role_a TO scott; ALTER USER scott GRANT CONNECT THROUGH app_user WITH ROLE app_role_a; Now, hr has permission to connect to the database through the proxy user. Through the role you can restrict the hr's rights the are needed for the application only. If hr connects to the database directly all assigned role and permissions apply. Testing the Setup To test the setup you can use SQL*Plus and connect to your database: $ sqlplus app_user[hr]/abcd1234 Java Persistence API The Java Persistence API (JPA) is a fairly easy means to build applications that retrieve data from the database and put it into Java objects. You use plain old Java objects (POJOs) and mixin some Java annotations that define how the attributes of the object are used for storing data from the database into the Java object. Here is a sample for objects from the HR sample schema EMPLOYEES table. When using Java annotations you only specify what can not be deduced from the code. If your Java class name is Employee but the table name is EMPLOYEES, you need to specify the table name, otherwise it will fail. package demo.proxy.ejb; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @NamedQueries({ @NamedQuery(name = "Employee.findAll", query = "select o from Employee o") }) @Table(name = "EMPLOYEES") public class Employee implements Serializable { @Column(name="COMMISSION_PCT") private Double commissionPct; @Column(name="DEPARTMENT_ID") private Long departmentId; @Column(nullable = false, unique = true, length = 25) private String email; @Id @Column(name="EMPLOYEE_ID", nullable = false) private Long employeeId; @Column(name="FIRST_NAME", length = 20) private String firstName; @Column(name="HIRE_DATE", nullable = false) private Timestamp hireDate; @Column(name="JOB_ID", nullable = false, length = 10) private String jobId; @Column(name="LAST_NAME", nullable = false, length = 25) private String lastName; @Column(name="PHONE_NUMBER", length = 20) private String phoneNumber; private Double salary; @ManyToOne @JoinColumn(name = "MANAGER_ID") private Employee employee; @OneToMany(mappedBy = "employee") private List employeeList; public Employee() { } public Employee(Double commissionPct, Long departmentId, String email, Long employeeId, String firstName, Timestamp hireDate, String jobId, String lastName, Employee employee, String phoneNumber, Double salary) { this.commissionPct = commissionPct; this.departmentId = departmentId; this.email = email; this.employeeId = employeeId; this.firstName = firstName; this.hireDate = hireDate; this.jobId = jobId; this.lastName = lastName; this.employee = employee; this.phoneNumber = phoneNumber; this.salary = salary; } public Double getCommissionPct() { return commissionPct; } public void setCommissionPct(Double commissionPct) { this.commissionPct = commissionPct; } public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Timestamp getHireDate() { return hireDate; } public void setHireDate(Timestamp hireDate) { this.hireDate = hireDate; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List getEmployeeList() { return employeeList; } public void setEmployeeList(List employeeList) { this.employeeList = employeeList; } public Employee addEmployee(Employee employee) { getEmployeeList().add(employee); employee.setEmployee(this); return employee; } public Employee removeEmployee(Employee employee) { getEmployeeList().remove(employee); employee.setEmployee(null); return employee; } } JPA could be used in standalone applications and Java EE containers. In both worlds you normally create a Facade to retrieve or store the values of the Entities to or from the database. The Facade does this via an EntityManager which will be injected by the Java EE container. Here is sample Facade Session Bean for a Java EE container. package demo.proxy.ejb; import java.util.HashMap; import java.util.List; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; import oracle.jdbc.driver.OracleConnection; import org.eclipse.persistence.config.EntityManagerProperties; import org.eclipse.persistence.internal.jpa.EntityManagerImpl; @Stateless(name = "DataFacade", mappedName = "ProxyUser-TestEJB-DataFacade") @Remote @Local public class DataFacadeBean implements DataFacade, DataFacadeLocal { @PersistenceContext(unitName = "TestEJB") private EntityManager em; private String username; public Object queryByRange(String jpqlStmt, int firstResult, int maxResults) { // setSessionUser(); Query query = em.createQuery(jpqlStmt); if (firstResult 0) { query = query.setFirstResult(firstResult); } if (maxResults 0) { query = query.setMaxResults(maxResults); } return query.getResultList(); } public Employee persistEmployee(Employee employee) { // setSessionUser(); em.persist(employee); return employee; } public Employee mergeEmployee(Employee employee) { // setSessionUser(); return em.merge(employee); } public void removeEmployee(Employee employee) { // setSessionUser(); employee = em.find(Employee.class, employee.getEmployeeId()); em.remove(employee); } /** select o from Employee o */ public List getEmployeeFindAll() { Query q = em.createNamedQuery("Employee.findAll"); return q.getResultList(); } Putting Both Together To use Proxy Authentication with JPA and within a Java EE container you have to take care of the additional requirements: Use an OCI JDBC driver Provide the user name that connects through the proxy user Use an OCI JDBC driver To use the OCI JDBC driver you need to set up your JDBC data source file to use the correct JDBC URL. hr jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE))) oracle.jdbc.OracleDriver user app_user 62C32F70E98297522AD97E15439FAC0E SQL SELECT 1 FROM DUAL jdbc/hrDS Application Additionally you need to make sure that the version of the shared libraries of the OCI driver match the version of the JDBC driver in your Java EE container or Java application and are within your PATH (on Windows) or LD_LIBRARY_PATH (on most Unix-based systems). Installing the Oracle Database Instance Client software works perfectly. Provide the user name that connects through the proxy user This part needs some modification of your application software and session facade. Session Facade Changes In the Session Facade we must ensure that every call that goes through the EntityManager must be prepared correctly and uniquely assigned to this session. The second is really important, as the EntityManager works with a connection pool and can not guarantee that we set the proxy user on the connection that will be used for the database activities. To avoid changing every method call of the Session Facade we provide a method to set the username of the user that connects through the proxy user. This method needs to be called by the Facade client bfore doing anything else. public void setUsername(String name) { username = name; } Next we provide a means to instruct the TopLink EntityManager Delegate to use Oracle Proxy Authentication. (I love small helper methods to hide the nitty-gritty details and avoid repeating myself.) private void setSessionUser() { setSessionUser(username); } private void setSessionUser(String user) { if (user != null && !user.isEmpty()) { EntityManagerImpl emDelegate = ((EntityManagerImpl)em.getDelegate()); emDelegate.setProperty(EntityManagerProperties.ORACLE_PROXY_TYPE, OracleConnection.PROXYTYPE_USER_NAME); emDelegate.setProperty(OracleConnection.PROXY_USER_NAME, user); emDelegate.setProperty(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, "Always"); } } The final step is use the EJB 3.0 AroundInvoke interceptor. This interceptor will be called around every method invocation. We therefore check whether the Facade methods will be called or not. If so, we set the user for proxy authentication and the normal method flow continues. @AroundInvoke public Object proxyInterceptor(InvocationContext invocationCtx) throws Exception { if (invocationCtx.getTarget() instanceof DataFacadeBean) { setSessionUser(); } return invocationCtx.proceed(); } Benefits Using Oracle Proxy Authentification has a number of additional benefits appart from implementing the role model of your application: Fine grained access control for temporary users of the account, without compromising the original password. Enabling database auditing and logging. Better identification of performance bottlenecks. References Effective Oracle Database 10g Security by Design, David Knox TopLink Developer's Guide, Chapter 98

    Read the article

  • Multiple database with Spring+Hibernate+JPA

    - by ziftech
    Hi everybody! I'm trying to configure Spring+Hibernate+JPA for work with two databases (MySQL and MSSQL) my datasource-context.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"> <!-- Data Source config --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> </bean> <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${remote.jdbc.driver}" p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" p:password="${remote.jdbc.password}" /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactory" /> <!-- JPA config --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> <property name="persistenceXmlLocations"> <list value-type="java.lang.String"> <value>classpath*:config/persistence.local.xml</value> <value>classpath*:config/persistence.remote.xml</value> </list> </property> <property name="dataSources"> <map> <entry key="localDataSource" value-ref="dataSource" /> <entry key="remoteDataSource" value-ref="dataSourceRemote" /> </map> </property> <property name="defaultDataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="localjpa"/> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> </beans> each persistence.xml contains one unit, like this: <persistence-unit name="remote" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> PersistenceUnitManager cause following exception: Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [config/datasource-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation': no matching editors or conversion strategy found If left only one persistence.xml without list, every works fine but I need 2 units... I also try to find alternative solution for work with two databases in Spring+Hibernate context, so I would appreciate any solution new error after changing to persistenceXmlLocations No single default persistence unit defined in {classpath:config/persistence.local.xml, classpath:config/persistence.remote.xml} UPDATE: I add persistenceUnitName, it works, but only with one unit, still need help UPDATE: thanks, ChssPly76 I changed config files: datasource-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> </bean> <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${remote.jdbc.driver}" p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" p:password="${remote.jdbc.password}"> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> <property name="defaultPersistenceUnitName" value="pu1" /> </bean> <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> <property name="persistenceXmlLocation" value="${persistence.xml.location}" /> <property name="defaultDataSource" ref="dataSource" /> <!-- problem --> <property name="dataSources"> <map> <entry key="local" value-ref="dataSource" /> <entry key="remote" value-ref="dataSourceRemote" /> </map> </property> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="pu1" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactoryRemote" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="pu2" /> <property name="dataSource" ref="dataSourceRemote" /> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactory" /> <bean id="transactionManagerRemote" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactoryRemote" /> </beans> persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence 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_1_0.xsd" version="1.0"> <persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${local.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${local.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> <persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> </persistence> Now it builds two entityManagerFactory, but both are for Microsoft SQL Server [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu1 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu2 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server (but must MySQL) I suggest, that use only dataSource, dataSourceRemote (no substitution) is not worked. That's my last problem

    Read the article

  • how to solve the error in GWT ?

    - by megala
    I created one GWT project in eclipse.It contained the following codings Program 1:Creategroup package com.crimson.creategroup; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.users.User; @Entity(name="CreateGroup") public class Creategroup { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Key key; @Basic private User author; @Basic private String groupname; @Basic private String groupid; @Basic private String groupdesc; @Basic private String emailper; public Key getKey() { return key; } public void setAuthor(User author) { this.author = author; } public User getAuthor() { return author; } public void setGroupname(String groupname) { this.groupname = groupname; } public String getGroupname() { return groupname; } public void setGroupid(String groupid) { this.groupid = groupid; } public String getGroupid() { return groupid; } public void setGroupdesc(String groupdesc) { this.groupdesc = groupdesc; } public String getGroupdesc() { return groupdesc; } public void setEmailper(String emailper) { this.emailper = emailper; } public String getEmailper() { return emailper; } public Creategroup(String groupname,String groupid,String groupdesc ,String emailper) { this.groupname = groupname; this.groupid = groupid; this.groupdesc = groupdesc; this.emailper=emailper; } } Program 2:Creategroupservlet package com.crimson.creategroup; import java.io.IOException; import javax.persistence.EntityManager; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.util.logging.Logger; public class Creategroupservlet extends HttpServlet{ private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(Creategroupservlet.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String groupname=req.getParameter("gname"); String groupid=req.getParameter("groupdesc"); String groupdesc=req.getParameter("gdesc"); String email=req.getParameter("eperm"); if (groupname == null) { System.out.println("Complete all the details"); } if (user != null) { log.info("Greeting posted by user " + user.getNickname() + "\n " + groupname+"\n" + groupid + "\n" + groupdesc + "\n" + email); final EntityManager em = EMF.get(); try { Creategroup group = new Creategroup(groupname,groupid,groupdesc,email); em.persist(group); } finally { em.close(); } } else { throw new IllegalArgumentException("anonymous posts not permitted!"); } resp.sendRedirect("/group.jsp"); } } Program 3:EMF package com.crimson.creategroup; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class EMF { private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional"); private EMF() { } public static EntityManager get() { return emfInstance.createEntityManager(); } } Program 4:index.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="com.google.appengine.api.users.User" %> <%@ page import="com.google.appengine.api.users.UserService" %> <%@ page import="com.google.appengine.api.users.UserServiceFactory" %> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link type="text/css" rel="stylesheet" href="Group.css"> <title>Add Group into DataStore</title> </head> <body> <div id="nav"> <% UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user != null) { response.sendRedirect("/group.jsp"); %> <% } else { %> <a href="<%= userService.createLoginURL(request.getRequestURI()) %>">Sign in</a> <% } %> </div> <h1>Create Group</h1> <table> <tr> <td colspan="2" style="font-weight:bold;"> This demo uses secured resources, so you need to be logged into your Gmail account.</td> </tr> </table> </body> </html> program 5:group.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.util.List" %> <%@ page import="javax.persistence.EntityManager" %> <%@ page import="com.google.appengine.api.users.User" %> <%@ page import="com.google.appengine.api.users.UserService" %> <%@ page import="com.google.appengine.api.users.UserServiceFactory" %> <%@ page import="com.crimson.creategroup.Creategroup" %> <%@ page import="com.crimson.creategroup.EMF" %> <html> <body> <% UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user != null) { %> <p>Hello, <%= user.getNickname() %>! (You can <a href="<%= userService.createLogoutURL(request.getRequestURI()) %>">sign out</a>.)</p> <% } else { response.sendRedirect("/index.jsp"); } %> <% final EntityManager em = EMF.get(); try { String query = "select from " + Creategroup.class.getName(); List<Creategroup> groups = (List<Creategroup>) em.createQuery(query).getResultList(); if (groups.isEmpty()) { %> <p>This table not having any group</p> <% } else { for (Creategroup g : groups) { %> <p><b><%= g.getAuthor().getNickname() %></b> wrote:</p> <blockquote><%= g. getGroupname() %></blockquote> <blockquote><%= g. getGroupid() %></blockquote> <blockquote><%= g. getGroupdesc() %></blockquote> <blockquote><%= g. getEmailper() %></blockquote> <% } } } finally { em.close(); } %> <form action="/sign" method="post"> <input type="text" name="Groupname" size="25"> <input type="text" name="Groupid" size="25"> <input type="text" name="Groupdesc" size="250"> <input type="text" name="Emaildesc" size="25"> <div><input type="submit" value="CREATE GROUP" /></div> </form> </body> </html> Program 6:Web.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- Servlets --> <servlet> <servlet-name>Creategroupservlet</servlet-name> <servlet-class>com.crimson.creategroup.Creategroupservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Creategroupservlet</servlet-name> <url-pattern>sign in</url-pattern> </servlet-mapping> <!-- Default page to serve --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> Program 7:persistence.xml <?xml version="1.0" encoding="UTF-8" ?> <persistence 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_1_0.xsd" version="1.0"> <persistence-unit name="transactions-optional"> <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider</provider> <properties> <property name="datanucleus.NontransactionalRead" value="true"/> <property name="datanucleus.NontransactionalWrite" value="true"/> <property name="datanucleus.ConnectionURL" value="appengine"/> </properties> </persistence-unit> </persistence but is shows the following error Missing required argument 'module[s]' Google Web Toolkit 2.0.0 DevMode [-noserver] [-port port-number | "auto"] [-whitelist whitelist-string] [-blacklist blacklist-string] [-logdir directory] [-logLevel level] [-gen dir] [-codeServerPort port-number | "auto"] [-server servletContainerLauncher] [-startupUrl url] [-war dir] [-extra dir] [-workDir dir] module[s] How to solve this thanks in advance?

    Read the article

  • How to use EJB 3.1 DI in Servlet ? (Could not inject session bean by @EJB from web application)

    - by kislo_metal
    I am tying to merging web application(gwt, jpa) to an separate 2 application(business login in ejb/jpa and web client in gwt). Currently i can`t inject my beans from web application (simple servlet) I am using glassfish v3. module limbo(ejb jar) is in dependency of module lust (war). If I use lust with compiler output of limbo everything work perfect (if ejb in web application and the are deploying together as one application). Have I messed some container configuration ? Here is my steps: I have some limbo.jar (ejb-jar) deployed to ejb container. I do not use any ejb-jar.xml, only annotations. package ua.co.inferno.limbo.persistence.beans; import javax.ejb.Remote; @Remote public interface IPersistentServiceRemote { ArrayList<String> getTerminalACPList(); ArrayList<String> getBoxACPList(); ArrayList<String> getCNPList(); ArrayList<String> getCNSList(); String getProductNamebyID(int boxid); ArrayList<String> getRegionsList(String lang); long getSequence(); void persistEntity (Object ent); } package ua.co.inferno.limbo.persistence.beans; import ua.co.inferno.limbo.persistence.entitis.EsetChSchemaEntity; import ua.co.inferno.limbo.persistence.entitis.EsetKeyActionsEntity; @Local public interface IPersistentService { ArrayList<String> getTerminalACPList(); ArrayList<String> getBoxACPList(); ArrayList<String> getCNPList(); ArrayList<String> getCNSList(); String getProductNamebyID(int boxid); ArrayList<String> getRegionsList(String lang); long getSequence(); long persistPurchaseBox(EsetRegPurchaserEntity rp); void removePurchaseTempBox(EsetRegPurchaserTempEntity rpt); EsetRegionsEntity getRegionsById(long rid); void persistEntity (Object ent); } package ua.co.inferno.limbo.persistence.beans; import ua.co.inferno.limbo.persistence.entitis.EsetChSchemaEntity; import ua.co.inferno.limbo.persistence.entitis.EsetKeyActionsEntity; import ua.co.inferno.limbo.persistence.entitis.EsetRegBoxesEntity; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless(name = "PersistentService") public class PersistentServiceEJB implements IPersistentService, IPersistentServiceRemote{ @PersistenceContext(unitName = "Limbo") EntityManager em; public PersistentServiceEJB() { } ......... } Than i trying to use PersistentService session bean(included in limbo.jar) from web application in lust.war (the limbo.jar & lust.war is not in ear) package ua.co.lust; import ua.co.inferno.limbo.persistence.beans.IPersistentService; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "ServletTest", urlPatterns = {"/"}) public class ServletTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { service(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { service(request, response); } @EJB private IPersistentService pService; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String hi = pService.getCNPList().toString(); System.out.println("testBean.hello method returned: " + hi); System.out.println("In MyServlet::init()"); System.out.println("all regions" + pService.getRegionsList("ua")); System.out.println("all regions" + pService.getBoxACPList()); } } web.xm <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <servlet> <servlet-name>ServletTest</servlet-name> <servlet-class>ua.co.lust.ServletTest</servlet-class> </servlet> </web-app> When servelt is loading i ge 404 eror (The requested resource () is not available.) And errors in logs : global Log Level SEVERE Logger global Name-Value Pairs {_ThreadName=Thread-1, _ThreadID=31} Record Number 1421 Message ID Complete Message Class [ Lua/co/inferno/limbo/persistence/beans/IPersistentService; ] not found. Error while loading [ class ua.co.lust.ServletTest ] javax.enterprise.system.tools.deployment.org.glassfish.deployment.common Log Level WARNING Logger javax.enterprise.system.tools.deployment.org.glassfish.deployment.common Name-Value Pairs {_ThreadName=Thread-1, _ThreadID=31} Record Number 1422 Message ID Error in annotation processing Complete Message java.lang.NoClassDefFoundError: Lua/co/inferno/limbo/persistence/beans/IPersistentService; ejb jar was deployed with this info log : Log Level INFO Logger javax.enterprise.system.container.ejb.com.sun.ejb.containers Name-Value Pairs {_ThreadName=Thread-1, _ThreadID=26} Record Number 1436 Message ID Glassfish-specific (Non-portable) JNDI names for EJB PersistentService Complete Message [ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote#ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote, ua.co.inferno.limbo.persistence.beans.IPersistentServiceRemote] Log Level INFO Logger javax.enterprise.system.tools.admin.org.glassfish.deployment.admin Name-Value Pairs {_ThreadName=Thread-1, _ThreadID=26} Record Number 1445 Message ID Complete Message limbo was successfully deployed in 610 milliseconds. Do i nee to add some additional configuration in a case of injections from others application? Some ideas?

    Read the article

  • one to many jpa relationship

    - by user309944
    Hai I have created two table first table as student package com.crimson.rship; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity(name="student") public class student { @Id private String stumailid; @Basic private String fathername; @Basic private String mothername; @Basic private String doa; @Basic private String dob; public student(String stumailid,String fathername,String mothername,String doa,String dob) { // TODO Auto-generated constructor stub this.stumailid=stumailid; this.fathername=fathername; this.mothername=mothername; this.doa=doa; this.dob=dob; } public void setStumailid(String stumailid) { this.stumailid = stumailid; } public String getStumailid() { return stumailid; } public void setFathername(String fathername) { this.fathername = fathername; } public String getFathername() { return fathername; } public void setMothername(String mothername) { this.mothername = mothername; } public String getMothername() { return mothername; } public void setDoa(String doa) { this.doa = doa; } public String getDoa() { return doa; } public void setDob(String dob) { this.dob = dob; } public String getDob() { return dob; } } Second table as mark package com.crimson.rship; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; @Entity(name="mark") public class mark { @Id private String stumailid; @Basic private String fathername; @Basic private String mothername; @OneToMany(mappedBy="mark",targetEntity=student.class,fetch=FetchType.EAGER) private Collection orders; public mark(String stumailid,String fathername,String mothername) { // TODO Auto-generated constructor stub this.stumailid=stumailid; this.fathername=fathername; this.mothername=mothername; } public void setStumailid(String stumailid) { this.stumailid = stumailid; } public String getStumailid() { return stumailid; } public void setFathername(String fathername) { this.fathername = fathername; } public String getFathername() { return fathername; } public void setMothername(String mothername) { this.mothername = mothername; } public String getMothername() { return mothername; } public void setOrders(Collection orders) { this.orders = orders; } public Collection getOrders() { return orders; } } But this above coding working is not working correctly.can any one help me Thanks in advance

    Read the article

  • Eclipselink update existing tables

    - by javydreamercsw
    Maybe I got it wrong but i though that JPA was able to update an existing table (model changed adding a column) but is not working in my case. I can see in the logs eclipselink attempting to create it but failing because it already exists. Instead of trying an update to add the column it keeps going. (Had to remove some < so it displays) property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jwrestling"/ property name="javax.persistence.jdbc.password" value="password"/ property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/ property name="javax.persistence.jdbc.user" value="user"/ property name="eclipselink.ddl-generation" value="create-tables"/ property name="eclipselink.logging.logger" value="org.eclipse.persistence.logging.DefaultSessionLog"/ property name="eclipselink.logging.level" value="INFO"/ And here's the table with the change (online column added) [EL Warning]: 2010-05-31 14:39:06.044--ServerSession(16053322)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.0.v20100517-r7246): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'account' already exists Error Code: 1050 Call: CREATE TABLE account (ID INTEGER NOT NULL, USERNAME VARCHAR(32) NOT NULL, SECURITY_KEY VARCHAR(255) NOT NULL, EMAIL VARCHAR(64) NOT NULL, STATUS VARCHAR(8) NOT NULL, TIMEDATE DATETIME NOT NULL, PASSWORD VARCHAR(255) NOT NULL, ONLINE TINYINT(1) default 0 NOT NULL, PRIMARY KEY (ID)) Query: DataModifyQuery(sql="CREATE TABLE account (ID INTEGER NOT NULL, USERNAME VARCHAR(32) NOT NULL, SECURITY_KEY VARCHAR(255) NOT NULL, EMAIL VARCHAR(64) NOT NULL, STATUS VARCHAR(8) NOT NULL, TIMEDATE DATETIME NOT NULL, PASSWORD VARCHAR(255) NOT NULL, ONLINE TINYINT(1) default 0 NOT NULL, PRIMARY KEY (ID))") [EL Warning]: 2010-05-31 14:39:06.074--ServerSession(16053322)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.1.0.v20100517-r7246): org.eclipse.persistence.exceptions.DatabaseException After this it continues with the following. Am I doing something wrong or is a bug?

    Read the article

  • Struts2 Hibernate Login with User table and group table

    - by J2ME NewBiew
    My problem is, i have a table User and Table Group (this table use to authorization for user - it mean when user belong to a group like admin, they can login into admincp and other user belong to group member, they just only read and write and can not login into admincp) each user maybe belong to many groups and each group has been contain many users and they have relationship are many to many I use hibernate for persistence storage. and struts 2 to handle business logic. When i want to implement login action from Struts2 how can i get value of group member belong to ? to compare with value i want to know? Example I get user from username and password then get group from user class but i dont know how to get value of group user belong to it mean if user belong to Groupid is 1 and in group table , at column adminpermission is 1, that user can login into admincp, otherwise he can't my code: User.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.model; import java.io.Serializable; 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.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.Temporal; /** * * @author Administrator */ @Entity @Table(name="User") public class User implements Serializable{ private static final long serialVersionUID = 2575677114183358003L; private Long userId; private String username; private String password; private String email; private Date DOB; private String address; private String city; private String country; private String avatar; private Set<Group> groups = new HashSet<Group>(0); @Column(name="dob") @Temporal(javax.persistence.TemporalType.DATE) public Date getDOB() { return DOB; } public void setDOB(Date DOB) { this.DOB = DOB; } @Column(name="address") public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Column(name="city") public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name="country") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Column(name="email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name="usergroup",joinColumns={@JoinColumn(name="userid")},inverseJoinColumns={@JoinColumn( name="groupid")}) public Set<Group> getGroups() { return groups; } public void setGroups(Set<Group> groups) { this.groups = groups; } @Column(name="password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Id @GeneratedValue @Column(name="iduser") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } @Column(name="username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name="avatar") public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } } Group.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * * @author Administrator */ @Entity @Table(name="Group") public class Group implements Serializable{ private static final long serialVersionUID = -2722005617166945195L; private Long idgroup; private String groupname; private String adminpermission; private String editpermission; private String modpermission; @Column(name="adminpermission") public String getAdminpermission() { return adminpermission; } public void setAdminpermission(String adminpermission) { this.adminpermission = adminpermission; } @Column(name="editpermission") public String getEditpermission() { return editpermission; } public void setEditpermission(String editpermission) { this.editpermission = editpermission; } @Column(name="groupname") public String getGroupname() { return groupname; } public void setGroupname(String groupname) { this.groupname = groupname; } @Id @GeneratedValue @Column (name="idgroup") public Long getIdgroup() { return idgroup; } public void setIdgroup(Long idgroup) { this.idgroup = idgroup; } @Column(name="modpermission") public String getModpermission() { return modpermission; } public void setModpermission(String modpermission) { this.modpermission = modpermission; } } UserDAO /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.dao; import java.util.List; import org.dejavu.software.model.User; import org.dejavu.software.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; /** * * @author Administrator */ public class UserDAO extends HibernateUtil{ public User addUser(User user){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); return user; } public List<User> getAllUser(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<User> user = null; try { user = session.createQuery("from User").list(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.getTransaction().commit(); return user; } public User checkUsernamePassword(String username, String password){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); User user = null; try { Query query = session.createQuery("from User where username = :name and password = :password"); query.setString("username", username); query.setString("password", password); user = (User) query.uniqueResult(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } session.getTransaction().commit(); return user; } } AdminLoginAction /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.dejavu.software.view; import com.opensymphony.xwork2.ActionSupport; import org.dejavu.software.dao.UserDAO; import org.dejavu.software.model.User; /** * * @author Administrator */ public class AdminLoginAction extends ActionSupport{ private User user; private String username,password; private String role; private UserDAO userDAO; public AdminLoginAction(){ userDAO = new UserDAO(); } @Override public String execute(){ return SUCCESS; } @Override public void validate(){ if(getUsername().length() == 0){ addFieldError("username", "Username is required"); }if(getPassword().length()==0){ addFieldError("password", getText("Password is required")); } } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } other question. i saw some example about Login, i saw some developers use interceptor, im cant understand why they use it, and what benefit "Interceptor" will be taken for us? Thank You Very Much!

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >