How to integrate hibernate with spring? - spring

I am newbie in spring. using spring 3.0 mvc. I am creating a spring application, I have a login form,Any one please suggest how to integrate hibernate and its set up...

You can define Hibernate's Session Factory bean in Spring's application context of your application. Look at this example:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>dao/hibernate/Login.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
where:
dataSource - reference to some implementation of javax.sql.DataSource
mappingResources - list of Hibernate ORM mapping files (shoul be on the classpath)
hibernateProperties - some basic set of Hibernate properties, you should tell Hiberante at least what type of DB you are using
Then you can wire this bean into DAO classes of your application and perform CRUD operations using wired sessionFactory object.
Suggestion for the future: you should be more specific in your questions!

You can use Springfuse. It's a tool which build a maven projet with Spring, Spring-mvc and Hibernate. It can provides you some demos (very usefull for newbies).

Not really a tutorial but, for an overview of the Spring 3.0 web stack, I'd recommend... Overview of the Spring 3.0 Web Stack.
In this presentation from SpringOne 2009, Keith Donald discusses the Spring 3.0 web stack, key Spring Framework and Spring MVC features, demos of Spring MVC capabilities, REST support, validation support, automatic data conversion, data binding and validation, Joda Time support, Spring JavaScript, Dojo, Spring Web Flow, Spring Security, Spring BlazeDS, and the roadmap for the Spring web stack.
For the persistence, maybe have a look at JPA 2.0 and Spring 3.0 with Maven. But the documentation is still the best resource IMO. See the 13. "Object Relational Mapping (ORM) Data Access"
Regarding the IDE, Spring Tool Suite will indeed give you the best user experience
For example, refer below links:
http://www.mkyong.com/struts/struts-spring-hibernate-integration-example/
http://www.vaannila.com/spring/spring-hibernate-integration-1.html

Related

Setup JPA Console in Intellij using Spring

I'm trying to get the JPA console working in Intellij. I have added JPA to the project under facets. However, IDE is asking for a persistence.xml. I'm using Annotated Spring and don't have any direct mapping files. Anyone configured this before, and can help me? Thanks
Further information:
Without adding JavaEE stuff - I don't need this.
File->Project Structure - Under modules: add JPA to a single module. Do not add persistence.xml or orm.xml
Under facets: Add JPA. Leave XML config blank. Leave JPA Provider blank
View -> Tool windows -> Persistence
You will see the module name and the EntityManager as configured under your SpringContext.xml. On my system I have these properties referenced in this SpringContext.xml
# jdbc.X
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql:///someThing
jdbc.user=postgres
jdbc.pass=postgres
# hibernate.X
hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create
I then select in my Persistence window (in which I can now see all entities) - click console button. Select JPA console. This will get me the error outlined here {yes, I'm using Postgres}
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206186929-JPA-Console-without-persistence-xml
Note the two "TTs-" PostgreSQL9Dialectt
Further further information:
Wierd. If I move the dialect into the actual xml config
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
<!--<prop key="hibernate.enable_lazy_load_no_trans">true</prop>-->
</props>
</property>
[2017-01-04 13:03:46] java.lang.IllegalStateException: Transaction already active
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at com.intellij.jpa.remote.impl.RemoteQueryImpl$1.getResultList(RemoteQueryImpl.java:92)
at com.intellij.jpa.remote.impl.QueryResultImpl.ensureInitialized(QueryResultImpl.java:113)
at com.intellij.jpa.remote.impl.QueryResultImpl.getColumnInfos(QueryResultImpl.java:30)
at com.intellij.jpa.remote.impl.RemoteQueryResultImpl.getColumnInfos(RemoteQueryResultImpl.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Spring Cloud Config Server without Spring Boot

I have looked at spring-cloud-config client without Spring Boot and many others and have not found a convincing answer. So here it goes again:
Question:
Is it possible, in a Spring app, to use Spring Cloud Config server/client without the automagic configuration of Spring Boot? Is using Spring Boot a requirement for using these frameworks?
If it is:
Is there any documentation that clearly describes what needs to be done in order to enable Spring Cloud Config server/client without Spring Boot?
Is there any sample project that clearly describes what needs to be done in order to enable Spring Cloud Config server/client without Spring Boot??
I'm not aware of documentation or a sample project. However we are doing it in our projects.
You just need to include the configuration server URI as a property source, assuming you are using PropertySourcesPlaceholderConfigurer:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer" id="propertyPlaceholder">
<property name="locations">
<list>
<value>http://your-config-server.com:8888/application-${spring.profiles.active}.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
</bean>
You have to make sure to pass -Dspring.profiles.active=current_profile to the java command line, like you probably would have done with boot.

How to reuse spring integration beans in a single application?

I'm using spring integration to create multiple services (each running in their own JVM) with JMS endpoints.
Once retry, exception handling, etc is added, the configuration is no longer trivial. I have moved the spring integration into its own context file and import it in all services to have a consistent setup.
eg
<import resource="classpath:/spring/jmsEndpoint.xml"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="queueName">myServiceQueue</prop>
</props>
</property>
</bean>
<alias name="myBusinessLogic" alias="abstractJmsEndpoint"/>
<bean id="myBusinessLogic" class="..."/>
This configuration allows me to keep each individual service configuration simple, only requiring an override of an abstract bean and setting a few properties.
The problem is I now want multiple jms endpoints in the same service (jvm). As I can't import jmsEndpoint.xml multiple times, what is the best way to reuse the configuration?
See the dynamic-ftp sample - it uses a technique of creating instances of a parameterized application contexts, passing different properries into each. It's README also has links to forum discussions about how to make these contexts children of the main context, in cases where the child needs access to shared resources.

Using Spring Transactions in MyBatis API

We have developed a data persistence framework using Mybatis. The framework uses plain MyBatis APIs. (We were prohibited from using any mybatis-spring, do not ask… why?)
Now we have to integrate this persistence framework with another framework developed by other teams. This other framework heavily uses spring transactions for everything. Our persistent framework DAOs will be used by this framework within its own API ….that means the spring managed transactions will be propagated to MyBatis DAO. It is expected that our MyBatis based persistence framework should participate in spring managed transactions without any issues.
There are two options for us to make this work
(1)Change our persistent framework to use mybatis-spring module. Change DAOs to use mappers directly injected using spring and spring’s SqlSessionFactoryBean. I did build a small example simulating both the frameworks and everything works without any issue. The problem is with this approach that it requires changing almost all the DAOs to use spring injected mapper, extensively test the framework again. We simply do not have time available due to delivery timeline.
(2)Use mybatis-spring, define SqlSeeionFactory using spring – set the datasource and transaction manager used by other framework. Something like
<bean id="smpDataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="connectionCachingEnabled" value="true" />
<property name="URL"> <value>${db.thin.url}</value></property>
<property name="user"> <value>${db.user}</value></property>
<property name="password"><value>${db.password}</value>
</property>
</bean>
<bean id="dbTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="smpDataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="smpDataSource" />
<property name="typeAliasesPackage" value="spike.smp51.domain" />
<property name="mapperLocations" value="classpath*:spike/smp51/mappers/*.xml" </bean>
Then in applicataion code MyBatis DAO gets the sqlseesionfactory from spring like
public static SqlSessionFactory getSqlSessionFactory() throws Exception
{
DefaultSqlSessionFactory sessionFactory = (DefaultSqlSessionFactory)ctx.getBean("sqlSessionFactory");
return sessionFactory;
}
All DAOs already use SqlSeesionFactory to open and close sessions. Just replace that mybatis created sqlseeionfactory with spring created sqlseeionfactory. That way we will have only few lines of changes.
This approach is outlined here
http://mybatis.github.io/spring/using-api.html
The mybatis documentation warns about this approach – specifically that it will not participate in spring transactions.
When I tried the 2nd approach, our framework was able to participate in spring transactions. This is strange. Is the MyBatis documentation incorrect then? I did verify it extensively by creating various transaction boundaries using spring transactions + AOP . MyBatis DAOs are able to participate in spring managed transactions every time. Since this second approach will save us 90% of the development time – we really like to use it – but worried since MyBatis warns following this approach. Has anyone tried this approach? Any feedback is greatly appreciated.
Did you have any return on that ?
I'm wondering if in the doc they're talking about org.apache.ibatis.session.SqlSessionFactory from Mybatis-api while the SqlSessionFactory you're using is from the mybatis-spring lib : org.mybatis.spring.SqlSessionFactoryBean

How to perform anonymous authentication?

I always thought that acegi security is the same as spring security 3.0... but It seems to be wrong.
Unfortunately I was unable to find any acegi security docs.
I need to have an anonymous user with special role assigned into Security Context what I found about that was this.
But there's no AnonymousAuthenticationFilter in ACEGI - only AnonymousProcessingFilter. But how should I call it's id?
I tried this code:
<bean id="anonymousAuthFilter"
class="net.sf.acegisecurity.providers.anonymous.AnonymousProcessingFilter">
<property name="key" value="foobar"/>
<property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
</bean>
<bean id="anonymousAuthenticationProvider"
class="net.sf.acegisecurity.providers.anonymous.AnonymousAuthenticationProvider">
<property name="key" value="foobar"/>
</bean>
But I get nothing in my Security Context before I actually login. And that's bad=(
Any ideas?
acegi security is the old name of spring security. (in 2.0 or older I can't remember, it is to long ago)
I strongly recommend to use Spring Security 3.0. Attention: The Package Names and Jar Structure was Changed between Spring Security 3.0 und Spring Security 2.0.
So if you have current documentation you will need to translate it back to 2.0. This Blog Spring Security 3.0.0.M1 Released describe the changes.

Resources