Search Results

Search found 1291 results on 52 pages for 'persistence ignorance'.

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

  • JDO architecture: One to many relationship and cascading deleting

    - by user361897
    I’m new to object oriented database designs and I’m trying to understand how I should be structuring my classes in JDO for google app engine, particularly one to many relationships. Let’s say I’m building a structure for a department store where there are many departments, and each department has many products. So I’d want to have a class called Department, with a variable that is a list of a Product class. @PersistenceCapable public class Department { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private String deptID; @Persistent private String departmentName; @Persistent private List<Product>; } @PersistenceCapable public class Product { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private String productID; @Persistent private String productName; } But one Product can be in more than one Department (like a battery could be in electronics and household supplies). So the next question is, how do I not duplicate data in the OOD world and have only one copy of product data in numerous departments? And the next question is, let’s say I delete out a particular product, how do each of the departments know it was deleted?

    Read the article

  • What happens to thread as onDestroy is called when device is rotated

    - by Lakshmie
    I would like to know as to what will happen to the thread which has been created by an activity and the device is rotated. I have observed that the onDestroy method is called when this happens. Will the thread be killed too? If the thread is not killed, how can I reassociate the thread with the activity as a new instance of the activity is created on rotation. Thanks, Lakshmie

    Read the article

  • Domain model for an online WYSYWG webpage generator / runtime

    - by CharlieBrown
    Hi all, I'm using C#, MVC, NHibernate and StructureMap as my IoC container, and need some ideas regarding my domain model. The application I'm working has two parts: an Authoring part and a Runtime part. The idea is to allow the user to create a webpage in Authoring (mostly a form actually) by choosing from a set of predefined controls. That webpage will be later used as a form in a call center environment (Runtime part), or may be used in an intranet portal, etc. Basically something similar to what a CMS would do. The difference is, of course, that the webpage/form the author generates will be used and fulfilled in runtime, and that authros should be able to freely create the webpage they want without limitations. I have a draft working model that allows a RunController to iterate over the ScriptPage (my class for the "generated webpage") Controls collection and uses partial views to render each of them. Works kind of fine. Basically I have a common ScriptControl class, and then I can create for example a TextInputControl or a DropDownControl by inheriting from that base class. I can also figure out the Authoring part of the app, although that will surely be fun in itself for sure. :) The biggest problem I have now is persistance. In order to be flexible, I want to be able to add more controls, and template controls (think of an Address composite control) in sepparate DLLs, so I think having a relational model that handles very possible control is not the way to go. My current thinking is using a kind of ObjectStore: binary-serializing the ScriptPage object that contains the List collection and deserializing at Runtime, but I'm not sure how good will it work with NHibernate and how good the performance will be. Serializing a small "page" with 10 controls results in 7964 bytes, for example. Any ideas out there? Thanks in advance, excuse the length. ;)

    Read the article

  • Save objects to a database?

    - by Eric
    So far in my .Net coding adventures I've only had a need to save information to files. So I've used XmlSerializer and DataContractSerializer to serialize attributed classes to XML files. My next project, however, requires that I save and retrieve information from a SQL server database. I'm wondering what my options are for doing this. The current version of the app, which was not created by me, uses a lot of hard coded SQL commands. But now I'm trying to avoid doing anything where I have to read or write individual fields to or from the database or objects. I especially want to avoid a lot of hard coded SQL in my code. I like how the serializer classes just figure out how to read and write XML files based on the attributes and or public properties of the class. Is there something similar for a database rather then XML?

    Read the article

  • Entity framework 4 many-to-many insertion?

    - by Saxman
    Hi all, I'm not very familiar with the many-to-many insertion process using Entity Framework 4, POCO. I have a blog with 3 tables: Post, Comment, and Tag. A Post can have many Tags and a Tag can be in many Posts. Here are the Post and Tag models: public class Tag { public int Id { get; set; } [Required] [StringLength(25, ErrorMessage = "Tag name can't exceed 25 characters.")] public string Name { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Post { public int Id { get; set; } [Required] [StringLength(512, ErrorMessage = "Title can't exceed 512 characters")] public string Title { get; set; } [Required] [AllowHtml] public string Content { get; set; } public string FriendlyUrl { get; set; } public DateTime PostedDate { get; set; } public bool IsActive { get; set; } public virtual ICollection<Comment> Comments { get; set; } public virtual ICollection<Tag> Tags { get; set; } } Now when I'm adding a new post, I'm not sure what would be the right way to do. I'm thinking that I'll have a textbox where I can select multiple tags for that post (this part is already done), in my controller, I will check to see if the tag is already exists or not, if not, then I will insert the new tag. But I'm not even sure based on the models that I've created for EF, will they create a PostsTags table, or they are creating just a Tags and a Posts table and links between the two? How would I insert the new Post and set the tags to that post? Is it just newPost.Tags = Tags (where Tags are the one that got selected, do I even need to check to see if they already exists?), and then something like _post.Add(newPost);? Thanks.

    Read the article

  • How can i read back an object stored in a session?

    - by strakastroukas
    First of all, here comes the load part. Structure MainStruct Dim Ans1 As String Dim Ans2 As String End Structure Dim Build As New List(Of MainStruct) ... ... ... Session("MyData") = Build The question is how can i read back the contents of the list, stored in the Session? I mean something like... Build = Session("MyData").Ans1

    Read the article

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

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