Spring MVC with Spring Data - Tuong-Nguyen/Spring GitHub Wiki
To use Spring Data you must add some librabies:
slf4j-api | slf4j-log4j12 | log4j | spring-data-jpa | hibernate-entitymanager |
In this config we use the H2 to soter our database. We use hibernate to generate the database automatically.
@Configuration
@EnableJpaRepositories("spitter.web.models")
@EnableTransactionManagement
@ComponentScan("spitter.web.models")
public class DataConfiguration {
@Bean
public DataSource dataSource(){
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public EntityManagerFactory entityManagerFactory(){
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setPackagesToScan("spitter.web.models");
factory.setJpaProperties(jpaProperties);
factory.setJpaVendorAdapter(vendorAdapter);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
}- The
public DataSource dataSource()function define an datasource where will store our application data.
When you use
EmbeddedDatabaseBuilderthe datasource url default is: 'jdbc:h2:mem:testdb' and it is memory database. You can use anotherDataSourceto config your database:
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:file:D:/workspace/demoJPA");
dataSource.setUser("sa");
dataSource.setPassword("");
return dataSource;
* Import `DataConfiguration` to web config
```java
@Configuration
@EnableWebMvc
@MultipartConfig
@ComponentScan("spitter.web")
@Import(DataConfiguration.class) //import DataConfiguration
public class WebConfig extends WebMvcConfigurerAdapter {
...
}
- The
@Entityannotation specify an entity class. - The
@Table(name = "USER")annotation specify the table name it will be generated automatically by Hibernate - The
@Idannotation specify the primary key of table. - The
@Column(name = "ID")annotation specify the column name of table.
@Entity
@Table(name = "USER")
public class User {
@Id
@Column(name = "ID")
private String userId;
@Column(name = "PASS")
private String password;
private String retypePassWord;
@Column(name = "NAME")
private String userName;
@Column(name = "EMAIL")
private String email;
@Column(name = "GENDER")
private String gender;
@Column(name = "BIRTHDAY")
private Date birthday;
//get set method....
}- The Repository class is extended ib
JpaRepository( orCrubRepository,MongoRepository...) base class which provide the basic methods to work with database - To enable
@Repositoryannotation you need config@EnableJpaRepositories("spitter.web.models")in web config
@Repository
public interface UserReponsitory extends JpaRepository<User, String> {
}@Service
public class UserService {
@Autowired
private UserReponsitory reponsitory;
public List<User> findAll(){
return reponsitory.findAll();
}
public User findOne(String id){
return reponsitory.findOne(id);
}
public User save(User user){
return reponsitory.save(user);
}
}- To view the datasource you must add JPA Facet in you Project Structure:
- Click 'File' -> 'Project Structure...' menu.
- In 'Project Structure' window choose 'Facets' then click '+' button -> 'JPA' to add JPA Facet.
- Now you can open 'Presistence' window tool:
- CLick 'View' -> 'Tool Windows' then select 'Presistence' in the dropdown menu.
- In your 'Presistence' window you can watch the entities you declared. And you can watch the ER Diagram, execute an SQL query form Console window.
- If you couldn't execute SQL qurey you must check the EntityManagerFactory's assign datasource.
- Right click 'entityManagerFactory' then select 'Assign Data Source ...' in the popup menu.
- In 'Assign Data Source' choose an datasource to assign.
- If you don't have an data source you can create in 'DataSource' tool window:
- In 'View' -> 'Tool Windows...' select 'DataSource'.
- In 'DataSource' window click '+' button to add new data source.