Spring + Hibernate project configuration (Java class version)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.