spring集成mongodb

public class Country implements Serializable {
    //实体类参考本人博客地址:https://blog.youkuaiyun.com/yl_hahha/article/details/80208161\
    @Id
    private String id;
    private String countryname;
    private String countrycode;

    public Country() {
    }

    //idea 生成构造器的快捷键  alt+insert
    public Country(String countryname, String countrycode) {
        this.countryname = countryname;
        this.countrycode = countrycode;
    }

    public String getId() {
        return id;
    }

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

    public String getCountryname() {
        return countryname;
    }
    public void setCountryname(String countryname) {
        this.countryname = countryname;
    }
    public String getCountrycode() {
        return countrycode;
    }
    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }
    @Override
    public String toString() {
        return "Country [id=" + id + ", countryname=" + countryname + ", countrycode=" + countrycode + "]";
    }
}
``
public interface CountryRepository extends MongoRepository<Country,String> {
    public Country findByCountrycode(String firstName);
    public List<Country> findByCountryname(String lastName);
}

@SpringBootApplication
public class DemoApplication implements CommandLineRunner{
@Autowired
private CountryRepository countryRepository;
//mongodb 下载地址 :http://dl.mongodb.org/dl/win32/x86_64
//配置 mongodb:http://www.runoob.com/mongodb/mongodb-window-install.html

/**
 * com.mongodb.MongoSocketOpenException: Exception opening socket
 *  确定服务是否启动成功 浏览器访问url localhost
 *  E11000 duplicate key error collection: springboot-db.country index: _id_ dup key: { : 0 }
 *  加注解@id
 * @param args
 */
public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
    countryRepository.deleteAll();
    countryRepository.save(new Country("bj","bj"));
    countryRepository.save(new Country("bj1","bj2"));
    List<Country> all = countryRepository.findAll();
    for (Country c:all){
        System.out.print(c);
    }
    for (Country b : countryRepository.findByCountryname("bj")) {
        System.out.println(b);
    }
}

}
“`项目地址,点击

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值