package com.avicsafety.webapp.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class User { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private Integer age;}
数据访问层
package com.avicsafety.webapp.dao;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;import com.avicsafety.webapp.model.User;public interface UserRepository extends JpaRepository { User findByName(String name); User findByNameAndAge(String name, Integer age); @Query("from User u where u.name=:name") User findUser(@Param("name") String name);}
逻辑层的接口和实现
package com.avicsafety.webapp.service;import com.avicsafety.webapp.model.User;public interface IUserService { public void AddUser(User user);}
package com.avicsafety.webapp.service.impl;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.avicsafety.webapp.dao.UserRepository;import com.avicsafety.webapp.model.User;import com.avicsafety.webapp.service.IUserService;@Servicepublic class UserServiceImpl implements IUserService { private static final Log logger = LogFactory.getLog(UserServiceImpl.class); @Autowired UserRepository dao; @Override public void AddUser(User user) { // TODO Auto-generated method stub dao.save(user); logger.info("add user"); }}
控制层
package com.avicsafety.webapp;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.avicsafety.webapp.model.User;import com.avicsafety.webapp.service.IUserService;@RestController@EnableAutoConfiguration@SpringBootApplication public class MyApplication { @Autowired private IUserService userService; @RequestMapping("/") String home() { User user = new User(); user.setName("shili"); user.setAge(11); userService.AddUser(user); return "ok"; } public static void main(String[] args) throws Exception { SpringApplication.run(MyApplication.class, args); }}