1. Write Test Cases
Description: I can easily configure the bean to facilitate dependency injection by using Spring's reason
Where Hibernateconfig is the bean's configuration file
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (classes=hibernateconfig.class) public Class TestMessage {@Autowiredprivate sessionfactory sessionfactory; @Testpublic void Test () {Session session = Sessionfactory.opensession (); org.hibernate.Transaction tx = session.begintransaction (); Message message = new Message ("Hello World"); Long msgId = (long) session.save (message); Tx.commit (); Session.close ();}}
2. Implement DataSource and sessionfactory two beans in Hibernateconfig
Where @componentscan has the function of automatic scanning
@Configuration @componentscanpublic class Hibernateconfig {@Beanpublic DataSource DataSource () {Basicdatasource DataSource = new Basicdatasource (); Datasource.seturl ("Jdbc:mysql:Localhost:3306/shopping "); Datasource.setdriverclassname ("Com.mysql.jdbc.Driver"); Datasource.setusername ("Root"); Datasource.setpassword (""); return dataSource;} @Beanpublic Localsessionfactorybean Sessionfactory(DataSource DataSource){//auto-correlate other bean:datasourcelocalsessionfactorybean SFB = new Localsessionfactorybean (); Sfb.setdatasource (DataSource) Sfb.setpackagestoscan (new string[] {"Model"}),//sfb.setmappingresources (new string[] {"Spitter.hbm.xml"}); Properties Props = new properties (); Props.setproperty ("Hibernate.dialect", "Org.hibernate.dialect.MySQLDialect"); Props.setproperty ("Hibernate.hbm2ddl.auto", "Update"); Props.setproperty ("Hibernate.show_sql", "true"); sfb.sethibernateproperties (props); return SFB;}}
Where the sessoinfactory is involved, the DataSource will be associated with datasource and injected.
Spring + Hibernate project configuration (Java class version)