0

im still beginner with java and spring , i have already stored table in mysql named as Offers, im trying to fetch the data row by row where the Status == 0, my table looks like:

-------------+------------+------------+------------+--------------+--------+--------+--------+--------+--------------+
| Msisdn      | Entry_Date | Start_Date | End_Date   | Service_Type | Status | Parm_1 | Parm_2 | Parm_3 | Process_Date |
+-------------+------------+------------+------------+--------------+--------+--------+--------+--------+--------------+
| 7777777777  | 2019-01-11 | 2019-02-15 | 2019-03-03 | 1            |      1 | 1      | 1      | 1      | 2019-10-15   |
| 7888888899  | 2019-01-11 | 2019-02-12 | 2019-03-03 | 1            |      0 | 1      | 1      | 1      | 2019-10-15   |
| 799999999   | 2019-01-11 | 2019-02-10 | 2019-03-03 | 1            |      0 | 1      | 1      | 1      | 2019-10-15   |
| 79111111111 | 2019-01-28 | 2019-02-27 | 2019-03-03 | 1            |      0 | 1      | 1      | 1      | 2019-10-15   |
+-------------+------------+------------+------------+--------------+--------+--------+--------+--------

when i try to run my code its return

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.example.accessingdatajpa.Offers

Offers

package com.example.accessingdatajpa;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;


@Entity
public class Offers {

    @GeneratedValue(strategy=GenerationType.AUTO)
    private String Msisdn;
    private String Entry_Date;
    private String Start_Date;
    private String End_Date;
    private String Service_Type;
    private String Status;
    private String Parm_1;
    private String Parm_2;
    private String Parm_3;
    private String Process_Date;

    protected Offers() {}

    public Offers(String Msisdn, String Entry_Date, String Start_Date, String End_Date, String Service_Type, String Status, String Parm_1 ,String Parm_2, String Parm_3, String Process_Date) {
        this.Msisdn = Msisdn;
        this.Entry_Date = Entry_Date;
        this.Start_Date = Start_Date;
        this.End_Date = End_Date;
        this.Service_Type = Service_Type;
        this.Status = Status;
        this.Parm_1 = Parm_1;
        this.Parm_2 = Parm_2;
        this.Parm_3 = Parm_3;
        this.Process_Date = Process_Date;
    }

    @Override
    public String toString() {
        return String.format(
                "Offers[Msisdn='%s', Entry_Date='%s', Start_Date='%s', End_Date='%s', Service_Type='%s', Status='%s', Parm_1='%s', Parm_2='%s', Parm_3='%s',Process_Date='%s']",
                Msisdn, Entry_Date, Start_Date, End_Date, Service_Type, Status, Parm_1,Parm_2,Parm_3,Process_Date);
    }

    public String getMsisdn() {
        return Msisdn;
    }

    public String getProcess_Date() {
        return Process_Date;
    }

    public String getEntry_Date() {
        return Entry_Date;
    }

    public String getStart_Date() {
        return Start_Date;
    }

    public String getEnd_Date() {
        return End_Date;
    }

    public String getService_Type() {
        return Service_Type;
    }

    public String getStatus() {
        return Status;
    }

    public String getParm_1() {
        return Parm_1;
    }

    public String getParm_2() {
        return Parm_2;
    }

    public String getParm_3() {
        return Parm_3;
    }
}

OffersRepository

package com.example.accessingdatajpa;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface OffersRepository extends CrudRepository<Offers, String> {

    List<Offers> findByStatus(String Status);

    Offers findByMsisdn(String Msisdn);
}

AccessingDataJpaApplication

package com.example.accessingdatajpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class AccessingDataJpaApplication {

    private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);

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

    @Bean
    public CommandLineRunner demo(OffersRepository repository) {
        return (args) -> {

            // fetch by status =0
            log.info("Offers found with findByStatus('0'):");
            log.info("--------------------------------------------");
            repository.findByStatus("0").forEach(on -> {
                log.info(on.toString());
            });
            log.info("");
        };
    }

}

test file

package com.example.accessingdatajpa;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
public class OffersRepositoryTests {
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private OffersRepository offer;

    @Test
    public void testFindByStatus() {
        Offers Offer = new Offers();
        entityManager.persist(Offer);

        List<Offers> findByStatus = offer.findByStatus(Offer.getStatus());

        assertThat(findByStatus).extracting(Offers::getStatus).containsOnly(Offer.getStatus());
    }
}
yong shi
  • 55
  • 1
  • 2
  • 10
  • 1
    You need to do like @Id @GeneratedValue(strategy=GenerationType.AUTO) private String Msisdn; – K.D Oct 16 '19 at 12:30

4 Answers4

1

I see quite few mistakes there:

1st

Add @Id annotation to msisdn

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private String Msisdn;

2nd

Add @Repository annotation to OffersRepository

@Repository
public interface OffersRepository extends CrudRepository<Offers, String> {

    List<Offers> findByStatus(String Status);

    Offers findByMsisdn(String Msisdn);
}

3rd

Add an autowired bean of type OffersRepository to your AccessingDataJpaApplication class and remove the parameter OffersRepository repository from your method public CommandLineRunner demo(OffersRepository repository)

@SpringBootApplication
public class AccessingDataJpaApplication {

    private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);

    @Autowired
    private OffersRepository repository;

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

    @Bean
    public CommandLineRunner demo() {
        return (args) -> {

            // fetch by status =0
            log.info("Offers found with findByStatus('0'):");
            log.info("--------------------------------------------");
            repository.findByStatus("0").forEach(on -> {
                log.info(on.toString());
            });
            log.info("");
        };
    }

}

4th

If you want to use CommandLineRunner, you need to implement it. You can do in a very simple way, by just implementing in your bootstrap class.

AccessingDataJpaApplication.java

@SpringBootApplication
public class AccessingDataJpaApplication implements CommandLineRunner {

    @Autowired
    private OffersRepository repository;

    private static final Logger log = LoggerFactory.getLogger(AccessingDataJpaApplication.class);

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

    @Override
    public void run(String...args) {
        log.info("Offers found with findByStatus('0'):");
        log.info("--------------------------------------------");
        repository.findByStatus("0").forEach(on - >{
            log.info(on.toString());
        });
        log.info("");
    }

}
Matheus
  • 3,058
  • 7
  • 16
  • 37
  • Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accessingDataJpaApplication': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with – yong shi Oct 16 '19 at 20:51
  • name 'offersRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.example.accessingdatajpa.OffersRepository.findByStatus(java.lang.String)! Unable to locate Attribute with the the given name [status] on this ManagedType [com.example.accessingdatajpa.Offers] – yong shi Oct 16 '19 at 20:53
  • By convention, usually properties starts with lower case. Rename the property `Status` to `status` in your `Offers` class. `private String status` – Matheus Oct 16 '19 at 21:02
  • thank you its worked , but the problem it does not print out the result on the console – yong shi Oct 17 '19 at 06:11
  • Well, that's because you're not printing anything to the console. If you want to use CommandLineRunner, you need to implement it. I've updated my answer. Take a look – Matheus Oct 17 '19 at 12:18
  • thank you its worked fine , can you help me with this question : https://stackoverflow.com/questions/58582177/jpa-with-https-request-multithreading-spring/58584987#58584987 – yong shi Oct 28 '19 at 08:41
0

Offers has no primary key. You have to annotate the primary key attribute with @Id

Like

@Id
private Integer id;
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • its return this warning each time i run code : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2019-10-16 16:13:01.855 ERROR 16835 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in com.example.accessingdatajpa.AccessingDataJpaApplication: Unsatisfied dependency expressed through method 'demo' parameter 0; nested exception is org.springframework.beans.factor – yong shi Oct 16 '19 at 13:14
0

You need to do like:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private String Msisdn;
K.D
  • 407
  • 3
  • 10
0

You are missing a field annotated with @Id. Each @Entity needs an @Id - this is given to the primary key in the database. On your entity class specify the annotations like :

@Entity
@Table(name = "OFFERS")
public class Offers {

   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   @Column(name = "Msisdn")
   private String Msisdn;

   @Column(name = "Entry_Date")   
   private String Entry_Date;

   @Column(name = "Start_Date")
   private String Start_Date;

   @Column(name = "End_Date")
   private String End_Date;

   @Column(name = "Service_Type")
   private String Service_Type;

   @Column(name = "Status")
   private String Status;

   @Column(name = "Parm_1")
   private String Parm_1;

   @Column(name = "Parm_2")
   private String Parm_2;

   @Column(name = "Parm_3")
   private String Parm_3;

   @Column(name = "Process_Date")
   private String Process_Date;
   //Setters and getters
}

It is okay , not to specify the table and column using the annotation if your column and table name adhers to the Implicit naming strategy.

The placement of the @Id annotation marks the persistence state access strategy.The identifier uniquely identifies each row in that table. By default, the name of the table is assumed to be the same as the name of the entity. To explicitly give the name of the table or to specify other information about the table, we would use the javax.persistence.Table annotation.A logical name can be either explicitly specified by the user (using @Column or @Table e.g.) or it can be implicitly determined by Hibernate through an ImplicitNamingStrategy contract.

Official Doc.

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39
  • can you help me with this question : https://stackoverflow.com/questions/58582177/jpa-with-https-request-multithreading-spring/58584987#58584987 – yong shi Oct 28 '19 at 08:41