[Spring] Pure java for Spring-hibernate integration

First import the corresponding jar package for Spring-hibernate ...

First import the corresponding jar package for Spring-hibernate



Then prepare the file for the database connectionHibernate.propertiesAlsoJdbc.properties

Hibernate.propertiesFile: Configure the hibernate dialect and automatic table building

hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create

Jdbc.propertiesFile: Configuration of dedicated hibernate connection database

jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:tcp://localhost/D:/H2/h2/bin
jdbc.username=sa
jdbc.password=123456


Create entity class Customer to map to table

package cn.qblank.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity // Entity classes are mapped to data tables, and class names are specified without specifying a table name //@Table public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String address; private boolean vip; 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isVip() { return vip; } public void setVip(boolean vip) { this.vip = vip; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", vip=" + vip + "]"; } }

Write a CustomerDao interface at the dao layer

package cn.qblank.dao; import cn.qblank.entity.Customer; public interface CustomerDao { void create(Customer customer); void update(Customer customer); Customer find(Long id); void delete(Long id); }


Implement the class CustomerDao to implement the interface and implement all its methods

package cn.qblank.dao.impl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import cn.qblank.dao.CustomerDao; import cn.qblank.entity.Customer; @Repository @Transactional public class CustomerDaoImpl implements CustomerDao { @Autowired private SessionFactory sessionFactory; @Override public void create(Customer customer) { System.out.println("create..."); Session session = sessionFactory.openSession(); // crud session.save(customer); } @Override public void update(Customer customer) { System.out.println("update..."); Session session = sessionFactory.openSession(); try { session.getTransaction().begin(); // crud session.update(customer); session.getTransaction().commit(); } catch (Exception ex) { session.getTransaction().rollback(); } finally { session.close(); } } @Override public Customer find(Long id) { return sessionFactory.getCurrentSession().get(Customer.class, id); } @Override public void delete(Long id) { System.out.println("delete"); Session session = sessionFactory.getCurrentSession(); Customer customer = new Customer(); customer.setId(id); session.delete(customer); } }


Create Config Class

package cn.qblank.test; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration //configuration file @ComponentScan("cn.qblank.dao") //Scanning dao layer @PropertySource("classpath:jdbc.properties") //Introducing an external property file to Enviroment @EnableTransactionManagement public class Config { @Bean public LocalSessionFactoryBean sessionFactory(DataSource dataSource) { LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setPackagesToScan("cn.qblank.entity"); // Automatically scan and register entity classes return factoryBean; } @Bean // Dependent on Environment public DataSource dataSource(Environment env) { DriverManagerDataSource ds = new DriverManagerDataSource(); // env.getProperty("someKey") Gets the attribute value ds.setDriverClassName(env.getProperty("jdbc.driverClassName")); ds.setUrl(env.getProperty("jdbc.url")); ds.setUsername(env.getProperty("jdbc.username")); ds.setPassword(env.getProperty("jdbc.password")); return ds; } //Create Transaction Management Class @Bean public PlatformTransactionManager transactionManager(SessionFactory sessionFactory){ HibernateTransactionManager transactionManager=new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory); return transactionManager; } }

Test last

package cn.qblank.test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import cn.qblank.dao.CustomerDao; import cn.qblank.entity.Customer; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); CustomerDao customerDao = context.getBean(CustomerDao.class); Customer customer = new Customer(); customer.setName("Zhao Six"); customer.setAddress("Changsha, Hunan"); customer.setVip(true); customerDao.create(customer); // Customer customer = customerDao.find(1L); // System.out.println(customer); // customerDao.delete(3l); context.close(); } }

Run result:



Here we add an exception at the dao layer:

@Override public void create(Customer customer){ System.out.println("create..."); Session session = sessionFactory.getCurrentSession(); // crud session.save(customer); throw new RuntimeException("My name is an exception"); }

Then test:

package cn.qblank.test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import cn.qblank.dao.CustomerDao; import cn.qblank.entity.Customer; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); CustomerDao customerDao = context.getBean(CustomerDao.class); Customer customer = new Customer(); customer.setName("Sparrow"); customer.setAddress("Changsha, Hunan"); customer.setVip(true); customerDao.create(customer); // Customer customer = customerDao.find(1L); // System.out.println(customer); // customerDao.delete(3l); context.close(); } }



You can see that an error occurred and the transaction rolled back successfully


8 July 2020, 10:43 | Views: 2785

Add new comment

For adding a comment, please log in
or create account

0 comments