Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jeet Prakash
Jeet Prakash

Posted on

     

No XML Spring and Hibernate Integration

Back in the pre Spring 3.1 days, we had to configure each and every bean into one of the spring configuration files which only happens to be an XML. And so if we were building a web application with Spring which is also using a relational database to store all its data, we needed to create a bean tag into one of those spring configuration XML files for reading out database connection properties to create a data source bean, which we then feed as a parameter to yet another bean tag to create a database session factory bean.

In this post we will be building a small restful web application with Spring MVC integrated with Hibernate to fetch the user record from MySQL database server and display it as a JSON response on the browser, without writing a single XML file. Furthermore we will also be doing away with tomcat’s web.xml leveraging latest Servlet 3.1 APIs and doing all of that configuration in our Java classes. So what are we waiting for!

Configuring Spring and Hibernate Integration

We can start by making a maven project with webapp archetype into any of our favourite IDE. And in itspom.xml file we can give all the dependencies as perthis gist. Notice that as one of the properties we have to setfailOnMissingWebXml to be false so that we can safely deleteweb.xml file.

Now we can start with configuring DispatcherServlet for our Spring MVC application which we can do in a single class:

publicclassAppConfigextendsAbstractAnnotationConfigDispatcherServletInitializer{@OverrideprotectedClass<?>[]getRootConfigClasses(){returnnewClass[]{HibernateConfig.class};}@OverrideprotectedClass<?>[]getServletConfigClasses(){returnnewClass[]{WebMvcConfig.class};}@OverrideprotectedString[]getServletMappings(){returnnewString[]{"/"};}}

A couple of points to note here:

  • This class is extending theAbstractAnnotationConfigDispatcherServletInitializer which automatically configureDispatcherServlet and the Spring application context.
  • IngetServletMappings() methods we return one or more paths thatDispatcherServlet will be mapped to.
  • IngetServletConfigClasses() we would be returning the@Configuration annotated classes that are having beans from whichDispatcherServlet will be loading its application context.
  • Classes returned fromgetRootConfigClasses() will be used to configure other application contexts that are created byContextLoaderListener and are shared among them.

This is all we need to configure ourDispatcherServlet, now let's look intoHibernateConfig.java andWebMvcConfig.java. InHibernateConfig.java we need to create all the beans that are necessary for handling interaction with database via Hibernate.

@Configuration@EnableTransactionManagementpublicclassHibernateConfig{@BeanpublicLocalSessionFactoryBeangetSessionFactory()throwsPropertyVetoException{LocalSessionFactoryBeanbean=newLocalSessionFactoryBean();PropertieshibernateProperties=newProperties();hibernateProperties.put("hibernate.dialect","org.hibernate.dialect.MySQLDialect");hibernateProperties.put("hibernate.show_sql","true");bean.setHibernateProperties(hibernateProperties);bean.setDataSource(getDataSource());bean.setPackagesToScan("com.spring5.app.dto");returnbean;}@BeanpublicComboPooledDataSourcegetDataSource()throwsPropertyVetoException{ComboPooledDataSourcedataSource=newComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/app-db?useSSL=false");dataSource.setUser("root");dataSource.setPassword("qwerty123");dataSource.setAcquireIncrement(10);dataSource.setIdleConnectionTestPeriod(0);dataSource.setInitialPoolSize(5);dataSource.setMaxIdleTime(0);dataSource.setMaxPoolSize(50);dataSource.setMaxStatements(100);dataSource.setMinPoolSize(5);returndataSource;}@BeanpublicJdbcTemplategetJdbcTemplate()throwsPropertyVetoException{JdbcTemplatetemplate=newJdbcTemplate();template.setDataSource(getDataSource());returntemplate;}@BeanpublicHibernateTransactionManagergetTransactionManager()throwsPropertyVetoException{HibernateTransactionManagertransactionManager=newHibernateTransactionManager();transactionManager.setSessionFactory(getSessionFactory().getObject());returntransactionManager;}}

InWebMvcConfig.java we need to create web specific beans, so as we are creating restful endpoints we would need appropriate message converters that would be required to convert Java objects to their proper JSON representations.

@Configuration@EnableWebMvc@ComponentScan("com.spring5.app")publicclassWebMvcConfigextendsWebMvcConfigurationSupport{@OverridepublicvoidconfigureMessageConverters(List<HttpMessageConverter<?>>converters){converters.add(customJackson2HttpMessageConverter());super.addDefaultHttpMessageConverters(converters);}@BeanpublicMappingJackson2HttpMessageConvertercustomJackson2HttpMessageConverter(){MappingJackson2HttpMessageConverterjsonConverter=newMappingJackson2HttpMessageConverter();ObjectMapperobjectMapper=newObjectMapper();objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);jsonConverter.setObjectMapper(objectMapper);returnjsonConverter;}}

Implementing REST and Persistence Layers

Now that we have configured all the important parts of our application we now need to implement a REST controller and corresponding Service and DAO that are quite straightforward.

@RestController()@RequestMapping("user")publicclassUserController{@AutowiredprivateUserServiceservice;@RequestMapping(value="{userId}",method=RequestMethod.GET)public@ResponseBodyServerResponsegetUser(@PathVariable("userId")LonguserId){returnthis.service.getUser(userId);}}
@RepositorypublicclassUserDaoImplimplementsUserDao{@AutowiredprivateSessionFactorysessionFactory;@OverridepublicUserDTOgetUser(LonguserId){TypedQuery<UserDTO>typedQuery=sessionFactory.getCurrentSession().createQuery("from UserDTO whereo">+userId.toString());returntypedQuery.getSingleResult();}}

And finally our service class is doing some mission critical stuff!

@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserDaouserDao;@Override@Transactional(readOnly=true)publicServerResponsegetUser(LonguserId){ServerResponseresponse=newServerResponse();UserDTOdto=userDao.getUser(userId);response.setUser(newUser(dto.getFirstName()+" "+dto.getLastName(),newLong(dto.getAge())));returnresponse;}}

Database schema

Lastly for the application to work we also need to create database schema in our MySQL server:

createtableifnotexists`users`(`id`intnotnullauto_increment,`firstName`varchar(20),`lastName`varchar(20),`age`int,primarykey(`id`));insertinto`users`values(1,"john","doe",29);

Source Code

I have not put all of the code on this post, but you can check out the working project fromthis github repository.

This article is already published on my personalblog.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I love everything #java, #spring and #angular. Trying to learn #ai, #machine #learning. Love #ui, #ux.
  • Location
    New Delhi
  • Work
    Full Stack Developer
  • Joined

More fromJeet Prakash

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp