spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate
1. Add dependencies to pom
<!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> org.springframework.bootspring-boot-starter-data-jpamysqlmysql-connector-java5.1.42
2. Add data source configuration (DataSource or something, a series of objects spring boot will inject to you, configuration Just configure it! )
spring.datasource.url=jdbc:mysql:spring.datasource.username==123456--name=-wait=10000-active=300-on-borrow=-size=20
#=====================jpa config================================ #实体类维护数据库表结构的具体行为:update/create/create-drop/validate/none spring.jpa.hibernate.ddl-auto=none #打印sql语句 spring.jpa.show-sql=true #格式化输出的json字符串 spring.jackson.serialization.indent_output=true
3. Create a new entity
@Entity @Table(name="user")public class User { @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id; @Column(name="number")private String number; @Column(name="name")private String name;public Integer getId() {return id; }public void setId(Integer id) {this.id = id; }public String getNumber() {return number; }public void setNumber(String number) {this.number = number; }public String getName() {return name; }public void setName(String name) {this.name = name; } }
4.dao Layer
public interface UserDao{ User getById(int id); User getByNumber(String number);int addUser(User user);void deleteUserById(int id); User updateUser(User user); }
@Repositorypublic class UserDaoImpl implements UserDao { @PersistenceContextprivate EntityManager entityManager; @Overridepublic User getById(int id) {//find by primary keyreturn this.entityManager.find(User.class,id); } @Overridepublic User getByNumber(String number) { Query query = this.entityManager.createQuery("from User u where u.number=:number",User.class); query.setParameter("number",number); User user = (User)query.getSingleResult();return user; } @Overridepublic int addUser(User user) {this.entityManager.persist(user);//print the id System.out.println(user.getId());return user.getId(); } @Overridepublic void deleteUserById(int id) { User user = this.entityManager.find(User.class,id); //关联到记录,方可删除this.entityManager.remove(user); } @Overridepublic User updateUser(User user) { User userNew = this.entityManager.merge(user);return userNew; } }
5.service layer
public interface UserService { User getById(int id); User getByNumber(String number);int addUser(User user,boolean throwEx);void deleteUserById(int id); User updateUser(User user); }
@Service @Transactionalpublic class UserServiceImpl implements UserService { @Autowiredprivate UserDao userDao; @Override @Transactional(readOnly = true)public User getById(int id) {return userDao.getById(id); } @Override @Transactional(readOnly = true)public User getByNumber(String number) {return userDao.getByNumber(number); } @Overridepublic int addUser(User user,boolean throwEx) {int id= this.userDao.addUser(user);if(throwEx){throw new RuntimeException("throw a ex"); }return id; } @Overridepublic void deleteUserById(int id) {this.userDao.deleteUserById(id); } @Overridepublic User updateUser(User user) {return this.userDao.updateUser(user); } }
6.controller layer
@Controller("user1") @RequestMapping("/jpa/user")public class UserController {/** * 日志(slf4j->logback) */private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowiredprivate UserService userService;/** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */@RequestMapping("/get/id/{id}") @ResponseBodypublic String getUserById(@PathVariable("id")String id){ logger.info("request /user/get/id/{id}, parameter is "+id); User user = userService.getById(Integer.parseInt(id));return JSONObject.toJSONString(user); }/** * 返回json格式数据 * @param number 编号 * @return 用户 */@RequestMapping("/get/number/{number}") @ResponseBodypublic User getUserByNumber(@PathVariable("number")String number){ User user = userService.getByNumber(number);return user; } @RequestMapping("/add/{number}/{name}") @ResponseBodypublic String addUser(@PathVariable("number")String number,@PathVariable("name")String name,boolean throwEx){ User user = new User(); user.setNumber(number); user.setName(name);int id = -1;try{ id = userService.addUser(user,throwEx); }catch (RuntimeException ex){ System.out.println(ex.getMessage()); }return String.valueOf(id); } @RequestMapping("/delete/{id}") @ResponseBodypublic void getUserById(@PathVariable("id")int id){this.userService.deleteUserById(id); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBodypublic User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name){ User user = new User(); user.setId(id); user.setNumber(number); user.setName(name);return userService.updateUser(user); } }
7. New way to use spring data jpa, more advanced
1.dao @Repositorypublic interface UserRepository extends JpaRepository<User, Integer> {/** * spring data jpa 会自动注入实现(根据方法命名规范) * @return */User findByNumber(String number); @Modifying @Query("delete from User u where u.id = :id")void deleteUser(@Param("id")int id); }2.servicepublic interface UserService { User findById(int id); User findByNumber(String number); List<User> findAllUserByPage(int page,int size); User updateUser(User user,boolean throwEx);void deleteUser(int id); } @Service @Transactionalpublic class UserServiceImpl implements UserService { @Autowiredprivate UserRepository userRepository; @Overridepublic User findById(int id) {return this.userRepository.findOne(id); } @Overridepublic User findByNumber(String number) {return this.userRepository.findByNumber(number); } @Overridepublic List<User> findAllUserByPage(int page,int size) { Pageable pageable = new PageRequest(page, size); Page<User> users = this.userRepository.findAll(pageable);return users.getContent(); } @Overridepublic User updateUser(User user,boolean throwEx) { User userNew = this.userRepository.save(user);if(throwEx){throw new RuntimeException("throw a ex"); }return userNew; } @Overridepublic void deleteUser(int id) {this.userRepository.deleteUser(id); } }3.controller @Controller("user2") @RequestMapping("/datajpa/user")public class UserController {/** * 日志(slf4j->logback) */private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowiredprivate UserService userService;/** * 返回text格式数据 * @param id 主键id * @return 用户json字符串 */@RequestMapping("/get/id/{id}") @ResponseBodypublic String getUserById(@PathVariable("id")String id){ logger.info("request /user/get/id/{id}, parameter is "+id); User user = userService.findById(Integer.parseInt(id));return JSONObject.toJSONString(user); }/** * 返回json格式数据 * @param number 编号 * @return 用户 */@RequestMapping("/get/number/{number}") @ResponseBodypublic User getUserByNumber(@PathVariable("number")String number){ User user = userService.findByNumber(number);return user; } @RequestMapping("/get/all/{page}/{size}") @ResponseBodypublic List<User> getAllUserByPage(@PathVariable("page")int page,@PathVariable("size")int size){return this.userService.findAllUserByPage(page,size); } @RequestMapping("/update/{id}/{number}/{name}") @ResponseBodypublic User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name,boolean throwEx){ User user = new User(); user.setId(id); user.setNumber(number); user.setName(name); User userNew = null;try{ userService.updateUser(user,throwEx); }catch (RuntimeException ex){ System.out.println(ex.getMessage()); }return userNew; } @RequestMapping("/delete/{id}") @ResponseBodypublic void getUserById(@PathVariable("id")int id){this.userService.deleteUser(id); } }
8. Inject jdbcTemplate and transactionTemplate, use the traditional way to operate the database, more flexible, the method is as follows
@Autowiredprivate JdbcTemplate jdbcTemplate; @Autowiredprivate TransactionTemplate transactionTemplate;/** * 手动控制事物测试 * @param throwEx */@Overridepublic void testTransactionManually(boolean throwEx) {try { transactionTemplate.execute(new TransactionCallback<Boolean>() {/** * 事物代码 * * @param transactionStatus 事物状态 * @return 是否成功 */@Overridepublic Boolean doInTransaction(TransactionStatus transactionStatus) { User user = new User(); user.setId(1);int a = new Random().nextInt(10); //0-9user.setNumber("10000u" + a); jdbcTemplate.update("UPDATE USER SET NUMBER=? WHERE ID=?", new Object[]{user.getNumber(), user.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});if (throwEx) {throw new RuntimeException("try throw exception"); //看看会不会回滚 }return true; } }); }catch (RuntimeException ex){ System.out.println(ex.getMessage()); } }/** * 手动执行jdbc测试 */@Overridepublic void testJdbcTemplate() { User user = new User();int a = new Random().nextInt(10); //0-9user.setNumber("10000i"+ a ); user.setName("name"+a);this.jdbcTemplate.update("INSERT into USER(NUMBER,NAME )VALUES (?,?)",user.getNumber(),user.getName()); }
So far, I have talked about how to operate the database in three ways (two jpa + jdbcTemplate). You can use it however you like. The above codes are all proven feasible in practice!
The above is the detailed content of spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics


![Windows ISO file too large BootCamp error [Fixed]](https://img.php.cn/upload/article/000/887/227/170831702395455.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
If you get the error message "The Windows ISO file is too large" when using BootCampAssistant on a Mac computer, this may be because the ISO file size exceeds the limit supported by BootCampAssistant. The solution to this problem is to use other tools to compress the ISO file size to ensure that it can be processed in BootCamp Assistant. BootCampAssistant is a convenient tool provided by Apple for installing and running Windows operating system on Mac computers. It helps users set up a dual-boot system, allowing them to easily choose to use MacOS or Wind at startup

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to migrate and integrate projects in GitLab Introduction: In the software development process, project migration and integration is an important task. As a popular code hosting platform, GitLab provides a series of convenient tools and functions to support project migration and integration. This article will introduce the specific steps for project migration and integration in GitLab, and provide some code examples to help readers better understand. 1. Project migration Project migration is to migrate the existing code base from a source code management system to GitLab

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

JUnit is a widely used Java unit testing framework in Spring projects and can be applied by following steps: Add JUnit dependency: org.junit.jupiterjunit-jupiter5.8.1test Write test cases: Use @ExtendWith(SpringExtension.class) to enable extension, use @Autowired inject beans, use @BeforeEach and @AfterEach to prepare and clean, and mark test methods with @Test.
