Using #Action annotation in openjpa - annotations

In my open jpa class, we have a method like this:
#Action(Action.ACTION_TYPE.CREATE)
public void createRecord(EntityObject fileStatus) {
EntityManager em = getEntityManager();
em.persist(fileStatus);
em.flush();
}
My question is with the #Action usage. I was of the impression that we use Annotations to avoid writing boilerplate code. In this particular method, what would be the boilerplate code that we would avoid by using the annotation? I think the method would look same even without the Annotation.

It's annotation used by IBM Rational Application Developer (RAD) - Related answer on IBM support page.
Annotations can be used for documenting purposes only - in that case they doesn't affect compiled code.
This one is most likely used by RAD to recognize specific JPA manager methods so it can list them in modeling tools there (this last is only mine guess).

Related

Can I use SpringData by itself [duplicate]

I'm trying to wire up Spring Data JPA objects manually so that I can generate DAO proxies (aka Repositories) - without using a Spring bean container.
Inevitably, I will be asked why I want to do this: it is because our project is already using Google Guice (and on the UI using Gin with GWT), and we don't want to maintain another IoC container configuration, or pull in all the resulting dependencies. I know we might be able to use Guice's SpringIntegration, but this would be a last resort.
It seems that everything is available to wire the objects up manually, but since it's not well documented, I'm having a difficult time.
According to the Spring Data user's guide, using repository factories standalone is possible. Unfortunately, the example shows RepositoryFactorySupport which is an abstract class. After some searching I managed to find JpaRepositoryFactory
JpaRepositoryFactory actually works fairly well, except it does not automatically create transactions. Transactions must be managed manually, or nothing will get persisted to the database:
entityManager.getTransaction().begin();
repositoryInstance.save(someJpaObject);
entityManager.getTransaction().commit();
The problem turned out to be that #Transactional annotations are not used automatically, and need the help of a TransactionInterceptor
Thankfully, the JpaRepositoryFactory can take a callback to add more AOP advice to the generated Repository proxy before returning:
final JpaTransactionManager xactManager = new JpaTransactionManager(emf);
final JpaRepositoryFactory factory = new JpaRepositoryFactory(emf.createEntityManager());
factory.addRepositoryProxyPostProcessor(new RepositoryProxyPostProcessor() {
#Override
public void postProcess(ProxyFactory factory) {
factory.addAdvice(new TransactionInterceptor(xactManager, new AnnotationTransactionAttributeSource()));
}
});
This is where things are not working out so well. Stepping through the debugger in the code, the TransactionInterceptor is indeed creating a transaction - but on the wrong EntityManager. Spring manages the active EntityManager by looking at the currently executing thread. The TransactionInterceptor does this and sees there is no active EntityManager bound to the thread, and decides to create a new one.
However, this new EntityManager is not the same instance that was created and passed into the JpaRepositoryFactory constructor, which requires an EntityManager. The question is, how do I make the TransactionInterceptor and the JpaRepositoryFactory use the same EntityManager?
Update:
While writing this up, I found out how to solve the problem but it still may not be the ideal solution. I will post this solution as a separate answer. I would be happy to hear any suggestions on a better way to use Spring Data JPA standalone than how I've solve it.
The general principle behind the design of JpaRepositoryFactory and the according Spring integration JpaRepositoryFactory bean is the following:
We're assuming you run your application inside a managed JPA runtime environment, not caring about which one.
That's the reason we rely on injected EntityManager rather than an EntityManagerFactory. By definition the EntityManager is not thread safe. So if dealt with an EntityManagerFactory directly we would have to rewrite all the resource managing code a managed runtime environment (just like Spring or EJB) would provide you.
To integrate with the Spring transaction management we use Spring's SharedEntityManagerCreator that actually does the transaction resource binding magic you've implemented manually. So you probably want to use that one to create EntityManager instances from your EntityManagerFactory. If you want to activate the transactionality at the repository beans directly (so that a call to e.g. repo.save(…) creates a transaction if none is already active) have a look at the TransactionalRepositoryProxyPostProcessor implementation in Spring Data Commons. It actually activates transactions when Spring Data repositories are used directly (e.g. for repo.save(…)) and slightly customizes the transaction configuration lookup to prefer interfaces over implementation classes to allow repository interfaces to override transaction configuration defined in SimpleJpaRepository.
I solved this by manually binding the EntityManager and EntityManagerFactory to the executing thread, before creating repositories with the JpaRepositoryFactory. This is accomplished using the TransactionSynchronizationManager.bindResource method:
emf = Persistence.createEntityManagerFactory("com.foo.model", properties);
em = emf.createEntityManager();
// Create your transaction manager and RespositoryFactory
final JpaTransactionManager xactManager = new JpaTransactionManager(emf);
final JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
// Make sure calls to the repository instance are intercepted for annotated transactions
factory.addRepositoryProxyPostProcessor(new RepositoryProxyPostProcessor() {
#Override
public void postProcess(ProxyFactory factory) {
factory.addAdvice(new TransactionInterceptor(xactManager, new MatchAlwaysTransactionAttributeSource()));
}
});
// Create your repository proxy instance
FooRepository repository = factory.getRepository(FooRepository.class);
// Bind the same EntityManger used to create the Repository to the thread
TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
try{
repository.save(someInstance); // Done in a transaction using 1 EntityManger
} finally {
// Make sure to unbind when done with the repository instance
TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
}
There must be be a better way though. It seems strange that the RepositoryFactory was designed to use EnitiyManager instead of an EntityManagerFactory. I would expect, that it would first look to see if an EntityManger is bound to the thread and then either create a new one and bind it, or use an existing one.
Basically, I would want to inject the repository proxies, and expect on every call they internally create a new EntityManager, so that calls are thread safe.

Please help on equivalent concept for JBoss AOP aspect

I am using JBoss application server 6 and using JBoss AOP aspects in my application.
An example of aspect shown below:
public class DBAspect{
public Object accessDBConnection(FieldReadInvocation invocation) {
return dbConnection;
}
public Object accessDBConnection((FieldWriteInvocation invocation) {
throw exception;
}
}
Currently, these advice methods are applied to a private variable in class say DBUsage by binding it with this aspect.
I am migrating to a new application server and it is not supporting JBoss AOP. So, how do I implement this concept.
How can I implement this behavior. Please help.
Applying field get/set pointcuts to private field does not sound like good application or aspect design to me. Maybe refactoring your application would be a better idea. Anyway, in AspectJ you can use get() and set() pointcuts in order to intercept field get/set actions. If you want to access private fields, you might need to use a privileged aspect.
AspectJ quick reference
Privileged aspects
AspectJ pointcut types (incl. get/set)

EF: Entity Dependency injection

Does EF 6 allow dependency injection in my entities? Below is an example of what is needed.
class User
{
private IPasswordEncryptor _passwordEncryptor;
public User(IPasswordEncryptor passwordEncryptor)
{
_passwordEncryptor = passwordEncryptor;
}
...
}
So, I need to find a way to inject the IPasswordEncryptor into User in Entity Framework. It's a general question, I just provided an example above.
For those using a DI container, you might try to inject the
dependencies into the aggregate root. That leads to a whole host of
problems, which are so numerous I won’t derail a perfectly good post
by getting into it. Instead, there’s another, more
intention-revealing option: the double dispatch pattern.
Quoted from a post by Jimmy Bogard. Find that post (which includes an example) here: http://lostechies.com/jimmybogard/2010/03/30/strengthening-your-domain-the-double-dispatch-pattern/.

IOC vs New guidelines

Recently I was looking at some source code provided by community leaders in their open source implementations. One these projects made use of IOC. Here is sample hypothetical code:
public class Class1
{
private ISomeInterface _someObject;
public Class1(ISomeInterface someObject)
{
_someObject = someObject;
}
// some more code and then
var someOtherObject = new SomeOtherObject();
}
My question is not about what the IOCs are for and how to use them in technical terms but rather what are the guidelines regarding object creation. All that effort and then this line using "new" operator. I don't quite understand. Which object should be created by IOC and for which ones it is permissible to be created via the new operator?
As a general rule of thumb, if something is providing a service which may want to be replaced either for testing or to use a different implementation (e.g. different authentication services) then inject the dependency. If it's something like a collection, or a simple data object which isn't providing behaviour which you'd ever want to vary, then it's fine to instantiate it within the class.
Usually you use IoC because:
A dependency that can change in the future
To code against interfaces, not concrete types
To enable mocking these dependencies in Unit Testing scenarios
You could avoid using IoC in the case where you don't control the dependency, for example an StringBuilder is always going to be an StringBuilder and have a defined behavior, and you usually don't really need to mock that; while you might want to mock an HttpRequestBase, because it's an external dependency on having an internet connection, for example, which is a problem during unit tests (longer execution times, and it's something out of your control).
The same happens for database access repositories and so on.

What is the benefit of using Unity Application Block or DI in general with Entity Framework as in my sample case

In the pseudocode below I have 3 layers: UI, BL, and DL for ASP.NET WebForms app.
Can someone give me some pointers about why would I need to use Dependency Injection
and Unity here? I am using interfaces a lot (mostly for 3rd party components like Mail or File Parsers so I can replace them as needed without changing other layers), but I do not get why I should use interfaces on EF EntityObjects. I can not seem to find one example on the web which would show a practical advantage beyond theoretical unreal cases.
namespace Sample.ASP.NET.UI
{
using Sample.ASP.NET.BusinessLayer;
using Sample.ASP.NET.DataModel;
protected class AspxCodeFile
{
protected Page_Load()
{
GridView.DataSource=BusinesLayer.Products.GetProductsAsList();
}
}
}
namespace Sample.ASP.NET.BusinessLayer
{
using Sample.ASP.NET.DataModel;
protected class Products
{
public static List<Product> GetProductsAsList()
{
EdmxEntities DB=new EdmxEntities();
return DB.Products.ToList<Product>();
}
}
}
namespace Sample.ASP.NET.DataLayer
{
// wrapper namespace for Entity Framework designer
// generated code off SQL Server 2008 database
// where one of the tables is called Products
// and designer created Product EntityObject
// this Product entity is referenced in both
// UI and BL.
}
In your scenario you obviously don't need it. People use dependency injection when they need to inject dependencies and replace them with other implementation - most common reason is automated testing and mocking / faking / stubing dependencies. Another reasons are dynamic behaviors.
In addition to the points Ladislav has made, there are a few others: -
You can use Unity to decorate methods and classes with cross cutting concerns (in Unity these are called behaviours). You can use behaviours anywhere, but I have used this with EF to do things like: -
Automatic creation / save / cleanup of your object contexts
Automatic caching of e.g. reference data
Logging of method call times to find performance bottlenecks on the DAL
Slightly more design related, but using Dependency Inversion Principle you can more loosely couple your system so e.g. your UI does not reference the Business Layer (and potentially decoupled from EF entirely depending on how you're generating your entities).