springboot上使用hibernate报错总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nzzl54/article/details/81128008

这两天在试用hibernate,整合入springboot是没问题了,但是具体使用就有问题,大部分应该都是下面两个问题

1、required a bean of type 'org.hibernate.SessionFactory' that could not be found.

2、InvalidDataAccessApiUsageException 和 Write operations are not allowed in read-only mode

看例子代码比较容易,百度上面说的都很零散,这里我暂时使用的是HibernateDaoSupport里面自带的方法。

代码规范如上,Dao为数据操纵,Service为中间服务关联Dao和controller,controller为前端与Service的连接,主类为LanSpringTestApplication 。从上往下解释,注意红字部分为主要解决上面问题的关键

1、LanSpringTestApplication

@EnableJpaRepositories("com.example.lan.dao") // JPA扫描该包路径下的Repositorie
@EntityScan("com.example.lan.entity") // 扫描实体类
@EnableScheduling

@SpringBootApplication
public class LanSpringTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(LanSpringTestApplication.class, args);
    }
    
    @Bean  
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf){  
        return hemf.getSessionFactory();  
    }   
    
    //或
    /*@Bean
        public HibernateJpaSessionFactoryBean sessionFactory() {
            return new HibernateJpaSessionFactoryBean();
        }*/

}

完成后将下面的内容添加到application.properties配置文件中

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

扫描二维码关注公众号,回复: 4476935 查看本文章

2、ModelController,这个无非就是控制和接收前端请求,要想使用我们写的方法,声明即可

@Resource
    private TestService testService;

方法映射看具体的使用了,这里给我这边的方法

@RequestMapping("/testQuery")
	@ResponseBody
    public Map<String,Object> testQuery(@RequestBody String name) {
		Map<String,Object> m = new HashMap<>();
		try {
			int id = Integer.valueOf(name);
			List<TestVo> list = (List<TestVo>) voDao.findAll();
			System.err.println("sample started. data ="+list);
			m.put("ok", "查询成功");
			m.put("data",testService.queryUserById(id)); 
		}catch(Exception e) {
			e.printStackTrace();
			logger.info(e.getStackTrace().toString());
			m.put("error",e.getStackTrace().toString());
		}
		return m;
    }

3、DAO相关类

(1)BaseDao:用来继承类和写一些共用方法,也可以直接写到具体Dao中,如果没有共用的话

@Transactional
public class BaseDao extends HibernateDaoSupport {
    @Autowired 
    public void setSessionFactoryOverride(SessionFactory sessionFactory)
    { 
      super.setSessionFactory(sessionFactory); 
    }

  
   public SessionFactory initSessionFactory() {
       Configuration config = new Configuration().configure();
      //读取hibernate核心配置文件内容,创建session工厂
       return config.buildSessionFactory();
   }
}

(2)ModelDao接口声明方法,ModelDaoImpl实现类

@Repository
@Table(name="userinfo")
@Qualifier("modelDao")
public interface ModelDao{
    //查询
    public TestVo getUserById(int id);

}
@Repository("modelDaoImpl")
public class ModelDaoImpl extends BaseDao implements ModelDao{
     @PersistenceContext
     private EntityManager entityManager;
     @Autowired
    private SessionFactory factory;

    @Override
    public TestVo getUserById(int id) {
        // TODO Auto-generated method stub
        return (TestVo)getHibernateTemplate().get(TestVo.class,id);
    }

}

4、TestVo 实体类
 

@Entity //加入这个注解,就会进行持久化了
@Table(name="userinfo")
public class TestVo {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name="name")
    private String name;

//set和get方法省略

}

5、Service相关类

TestService接口声明方法,TestServiceImpl实现类

public interface TestService {
     public TestVo queryUserById(int id);
}
@Service
public class TestServiceImpl implements com.example.lan.service.TestService{
    @Autowired
    private ModelDaoImpl modelDaoImpl;

   @Override
    public TestVo queryUserById(int id) {
        // TODO Auto-generated method stub
        return modelDaoImpl.getUserById(id);
    }

}

参考来自:

https://blog.csdn.net/qq_27298687/article/details/77896609

https://blog.csdn.net/violet_echo_0908/article/details/51084884

猜你喜欢

转载自blog.csdn.net/nzzl54/article/details/81128008