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);
}
}
}
“`项目地址,点击