У меня есть простой проект гибернации, который должен вставить и выбрать запись из базы данных. Я установил Bean, интерфейс DAO и реализовал его в классе DAOImple.
Однако он не вставляет данные в таблицу. Основной выводит новый идентификатор, но по-прежнему в таблице не создается запись.
Это код, который у меня есть:
Program. java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Program {
public static void main(String args[])
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfigurations.class);
ProductDAO dao = context.getBean(ProductDAO.class);
System.out.println("Creating product");
dao.create(new Product("Chocklate", 17.9f));
System.out.println("Product created successfully");
System.out.println("***********************");
for(Product p : dao.findAll())
{
System.out.println(p);
}
}
}
SpringConfiguration. java
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
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.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
@Configuration
@ComponentScan("mypackage")
@PropertySource("classpath:application.properties")
public class SpringConfigurations {
/*@Autowired
Environment env;*/
@Autowired
private ApplicationContext context;
@Bean("hibernateTemplate")
HibernateTemplate getHibernateTemplate()
{
HibernateTemplate template = new HibernateTemplate(getSessionFactoryBean().getObject());
template.setCheckWriteOperations(false);
return template;
}
@Bean
public LocalSessionFactoryBean getSessionFactoryBean()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource( getDataSource());
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setPackagesToScan("mypackage");
return factoryBean;
}
@Bean
public HibernateTransactionManager getTransactionManager()
{
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactoryBean().getObject());
return transactionManager;
}
public DriverManagerDataSource getDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(getHibernateProperties().getProperty("connectionString"));
return dataSource;
}
public Properties getHibernateProperties()
{
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
props.put("hibernate.show_sql", true);
props.put("hibernate.connection.autocommit", true);
props.put("hibernate.hbm2ddl.auto", "update");
props.put("connectionString","jdbc:sqlserver://localhost;databaseName=myDB;integratedSecurity=true");
return props;
}
}
Product. java (Bean)
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="products")
public class Product {
private int id;
private String name;
private float price;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product( String name, float price) {
super();
this.name = name;
this.price = price;
}
public Product(int id, String name, float price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id") //in case the field is same name as the variable, no need to mention the name="id"
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="price")
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
ProductDAOImpl. java
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;
@Component
public class ProductDAOImpl implements ProductDAO {
@Autowired
HibernateTemplate hibernateTemplate;
@Transactional
public void create(Product product) {
Integer ret = (Integer) hibernateTemplate.save(product);
System.out.println(ret);
}
@Transactional
public void update(Product product) {
hibernateTemplate.update(product);
}
@Transactional
public void delete(Product product) {
hibernateTemplate.delete(product);
}
public Product find(int id) {
return hibernateTemplate.get(Product.class,id);
}
public List<Product> findAll() {
return hibernateTemplate.loadAll(Product.class);
}
}