本文主要是介绍Spring Boot学习之旅:(十四)整合hibernate,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在原有的基础上添加 mysql 连接和jpa 依赖
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
配置sessionFactory
@Configuration
public class SessionFactoryConfig {@Beanpublic HibernateJpaSessionFactoryBean sessionFactory() {return new HibernateJpaSessionFactoryBean();}
}
创建一个model
package com.wen.boot.model;import java.util.Date;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;import com.alibaba.fastjson.annotation.JSONField;@Entity
public class User {private int id;private String name;private int age;@JSONField(format="yyyy-mm-dd HH:mm")private Date createTime;private String remakes;/** serialize 是否需要序列化* @return the remakes*/@JSONField(serialize=false)public String getRemakes() {return remakes;}public void setRemakes(String remakes) {this.remakes = remakes;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}@Id@GeneratedValue(strategy=GenerationType.AUTO)public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
dao
public interface IUserDao {public User getUserById(int id);
}
dao 实现
@Repository("userDao")
public class UserDaoImpl implements IUserDao {@Resourceprivate SessionFactory sessionFactory;public User getUserById(int id) {Session session=sessionFactory.openSession();User user=session.get(User.class, id);session.close();return user;}
}
service
public interface IUserService {public User getUserById(int id);
}
service 实现
@Service
public class UserServiceImpl implements IUserService{@Resource(name="userDao")private IUserDao userDao; public User getUserById(int id) {return userDao.getUserById(id);}
}
controller
@RestController
@RequestMapping("/user")
public class HelloContreller {private Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredpublic IUserService userService;@GetMapping("/{id}")public User getUser(@PathVariable int id) {return userService.getUserById(id);}
}
启动工程 浏览器输入
http://localhost:8080/user/1
查看查询结果
本片文章只做整合hibernate 只做了简单的查询 如果还要实现其他的方法可以参考
http://blog.csdn.net/gwblue/article/details/24593113 这篇博客
文章地址:http://www.haha174.top/article/details/258855
项目源码: https://github.com/haha174/boot.git
欢迎关注,更多福利
这篇关于Spring Boot学习之旅:(十四)整合hibernate的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!