1

我正在尝试从我对 TwitterAPI 提出的请求中保存一些数据。我知道,我必须在 UpdateTweetsService 类中设置我想要的对象,但我现在知道如何解析它们。这是我到目前为止所拥有的:

UpdateTweetsService.java 类:

import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import java.util.List;


public class UpdateTweetsService {@Value("${screenName}")
private final Twitter twitter;

@Inject
public UpdateTweetsService(Twitter twitter) {
    this.twitter = twitter;

}
/**
 * Performs a Request to get the UserTimeline from Twitter API
 */

 public List<Tweet> tweets() {

        return twitter.timelineOperations().getUserTimeline("${screenName}");    
 }

Tweet.java 类:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "tweets")
public class Tweet {


    @Id
    @GeneratedValue
    @Column(columnDefinition = "INT unsigned")
    private Integer id;

    @NotEmpty
    @Length(max = 255)
    @Column(columnDefinition = "VARCHAR(255)", length = 255, nullable = false)
    private String profileImageUrl;

    @NotEmpty
    @Length(max = 64)
    @Column(columnDefinition = "VARCHAR(64)", length = 64, nullable = false)
    private String fromUser;

    @NotEmpty
    @Column(columnDefinition = "TEXT", nullable = false)
    private String text;

    @NotEmpty
    @Length(max = 255)
    @Column(columnDefinition = "VARCHAR(255)", length = 255, nullable = false)
    private String url;

    @NotEmpty
    @Column(columnDefinition = "FLOAT")
    private Float createDate;

    /*
     * Getter & Setter
     */

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getProfileImageUrl() {
        return profileImageUrl;
    }

    public void setProfileImageUrl(String profileImageUrl) {
        this.profileImageUrl = profileImageUrl;
    }

    public String getFromUser() {
        return fromUser;
    }

    public void setFromUser(String fromUser) {
        this.fromUser = fromUser;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Float getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Float createDate) {
        this.createDate = createDate;
    }   

}
4

1 回答 1

0

You can use Spring Data JPA to save your entities. Its very easy to setup your database with Spring Boot.

You can checkout the code in my Github repo, I updated it for this. I have used PostgreSql, you can easily change it to MySql by updating pom.xml and application.properties file as per below steps.

You need to follow below steps:

  1. Add spring-boot-starter-data-jpa and mysql dependencies in your pom.xml

    .....
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    
  2. Set the database config/properties in your application.properties

    .....
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
    spring.jpa.show-sql=true
    spring.jpa.database=mysql       
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
    spring.datasource.url=jdbc:mysql://localhost:3306/sakila
    spring.datasource.name=sakila
    spring.datasource.username=mysql
    spring.datasource.password=password
    
  3. Create an Entity class TweetEntity which you already did, but rename it from Tweet to something else to avoid confusion between your Tweet.class and org.springframework.social.twitter.api.Tweet.class

  4. Create Spring Data JPA Repositories interface for your entity.

    package com.rawsanj.tweet.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.rawsanj.tweet.entity.TweetEntity;
    
    /**
     * Spring Data JPA repository for the User entity.
     */
    public interface TweetZRepository extends JpaRepository<TweetEntity, Long> {
    
    }
    

    Just be defining above Spring Data Repository you get several methods (like save(Entity entity), findOne(Long Id), etc) already implemented.

  5. Let SpringBoot know your repository package, i.e. enable Jparepositories.

    @SpringBootApplication
    @EnableJpaRepositories("com.rawsanj.tweet.repository")
    public class Application {
    ....
    ..
    
  6. And finally update your Controller:

    package com.rawsanj.tweet.controller;
    ....
    import com.rawsanj.tweet.entity.TweetEntity;
    import com.rawsanj.tweet.repository.TweetZRepository ;
    
    @Controller
    @RequestMapping("/")
    public class HelloController {
    
        private TwitterTemplate twitterTemplate;
        private TweetZRepository tweetZRepository ;
    
        @Inject
        public HelloController(StreamService streamService, TwitterTemplate twitterTemplate, TweetZRepository tweetZRepository ) {
            this.streamService = streamService;
            this.twitterTemplate=twitterTemplate;
            this.tweetZRepository =tweetZRepository ;
        }
    
        @RequestMapping(value = "tweet/{search}/{count}",method=RequestMethod.GET)
        public String searchTwitter(Model model, @PathVariable String search, @PathVariable int count) {
            SearchResults results = twitterTemplate.searchOperations().search(
                    new SearchParameters(search)
                        .resultType(SearchParameters.ResultType.RECENT)
                        .count(count));
    
            List<Tweet> tweets = results.getTweets();        
            model.addAttribute("tweets", tweets);
    
            for (Tweet tweet : tweets) {            
                TweetEntity tweetEntity = new TweetEntity(tweet.getText(), tweet.getCreatedAt(), tweet.getFromUser(), tweet.getLanguageCode(), tweet.getLanguageCode());
                tweetZRepository.save(tweetEntity);
            }
            return "search";
        }
    }
    
于 2016-02-27T15:31:19.200 回答