如何在spring CRUD Repository中编写自定义查询

时间:2016-09-23 14:45:03

标签: spring-boot

我正在使用spring Boot开发应用程序。 这是我的代码。

UserSample.java
@Entity
public class UserSample {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long userId;
    private String userName;

    public UserSample() {
        super();
    }

    public UserSample(String userName) {
        super();
        this.userName = userName;

    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}
Interface is:


public interface UserSampleRepository extends CrudRepository<UserSample, Long> {

}

在主要班级

@SpringBootApplication
public class MainApplication implements CommandLineRunner {


    @Autowired
    UserSampleRepository usersampleRepo;

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        List<UserSample> userSample = new LinkedList<UserSample>();
        // load data to the table
        userSample.add(new UserSample("user1"));
        userSample.add(new UserSample("user2"));
        usersampleRepo.save(userSample);

        UserSample userInfo = usersampleRepo.findOne(1);

    }

}

我有内存数据库。在这里,我试图编写一个查询以通过用户名检索。 like userSampleRepo.findByUserName(String username); 我试过很多方法,但没有什么对我有用。有什么建议吗?

我尝试在界面中添加方法。

    public interface UserSampleRepository extends CrudRepository<UserSample, Long> {
        UserSample findByUserName(String username);

    }

created another class.

    @Repository
    public class UserSampleRepositoryImpl implements UserSampleRepository {

        @PersistenceContext
        private EntityManager em;

        @Override
        public UserSample findByUserName(String username) {
            TypedQuery<UserSample> query = em.createQuery("select c from UserSample c where c.userName = :username",
                    UserSample.class);
            query.setParameter("username", username);

            return query.getSingleResult();
        }

在大班中,我使用了这个陈述

@Autowired
    UserSampleRepositoryImpl usersampleRepo;
    UserSample userInfo = usersampleRepo.findByUserName("user1");

我收到此错误: “java.lang.IllegalStateException:无法执行CommandLineRunner” aused by:org.springframework.dao.EmptyResultDataAccessException:找不到查询的实体;嵌套异常是javax.persistence.NoResultException:找不到查询的实体

0 个答案:

没有答案