Neo4j-spring data 基本使用一

Neo4j 圖數(shù)據(jù)庫(kù)

善于維護(hù)數(shù)據(jù)間的關(guān)系

數(shù)據(jù)對(duì)象(節(jié)點(diǎn))是一種數(shù)據(jù)奥帘,需要單獨(dú)存儲(chǔ)繁调;數(shù)據(jù)節(jié)點(diǎn)間的關(guān)系(邊)也是一種數(shù)據(jù)馁菜,也需要維護(hù)存儲(chǔ)茴扁;

適用于:

           存儲(chǔ)維護(hù)數(shù)據(jù)間復(fù)雜的關(guān)系網(wǎng)絡(luò),便于按關(guān)系查詢相應(yīng)數(shù)據(jù)節(jié)點(diǎn)汪疮;

廢話不多說峭火,具體圖論、相關(guān)理論智嚷、應(yīng)用場(chǎng)景介紹...見其它資料卖丸;

開整應(yīng)用干貨

spring-boot 項(xiàng)目 spring-data jpa 使用neo4j

pom主要依賴

...
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath />
    </parent>
...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-http-driver</artifactId>
        </dependency>
...

application.yml配置

spring:
  data:
    neo4j:
      username: neo4j
      password: ******(密碼)
      uri: http://127.0.0.1:7474

Neo4jConfig

package com.fc.neo4j_demo.config;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;
@Configuration
@EnableAutoConfiguration
@EnableNeo4jRepositories(basePackages = "com.fc.neo4j_demo.dao.repository")
@EnableTransactionManagement
public class Neo4jConfiguration {
    @Bean
    public SessionFactory sessionFactory() {
        // 默認(rèn)為bolt,只有從配置文件修改后會(huì)變成http
        return new SessionFactory(configuration(), "com.fc.neo4j_demo.entity.neo4j");
    }
    @Value("${spring.data.neo4j.uri}")
    private String uri;
    @Value("${spring.data.neo4j.username}")
    private String name;
    @Value("${spring.data.neo4j.password}")
    private String password;
    @Bean
    public org.neo4j.ogm.config.Configuration configuration() {
        System.out.println();
        org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder().uri(uri)
                .credentials(name, password).build();
        return configuration;
    }
    @Bean("transactionManager")
    public Neo4jTransactionManager transactionManager() throws Exception {
        return new Neo4jTransactionManager(sessionFactory());
    }
    @Bean("neo4jTransactionTemplate")
    public TransactionTemplate neo4jTransactionTemplate(
            @Qualifier("transactionManager") Neo4jTransactionManager neo4jTransactionManager) {
        return new TransactionTemplate(neo4jTransactionManager);
    }
}

項(xiàng)目結(jié)構(gòu)

image.png

維護(hù)一個(gè)節(jié)點(diǎn)對(duì)象

// 節(jié)點(diǎn)基礎(chǔ)屬性  (這里所有繼承BaseNode的節(jié)點(diǎn)會(huì)自動(dòng)帶上 BaseNode 標(biāo)簽)
public class BaseNode {
    @Id
    @GeneratedValue
    private Long id;
    @Labels // 節(jié)點(diǎn)的標(biāo)簽(代表什么類型的節(jié)點(diǎn)) 可以自定義添加多個(gè)
    private Set<String> labels = new HashSet<>();
...

// Person節(jié)點(diǎn)
@NodeEntity(label = "Person") // 節(jié)點(diǎn)默認(rèn)標(biāo)簽名為Person
public class Person extends BaseNode {

    private Integer userId;
    private String userName;
    private String userPhone;
...

維護(hù)一個(gè)關(guān)系(邊)對(duì)象

// 所有Neo4j中的節(jié)點(diǎn)、(關(guān)系)邊 都需要有一個(gè)默認(rèn)的id屬性盏道,保存的是Neo4j中自己的數(shù)據(jù)主鍵稍浆,與業(yè)務(wù)無關(guān)
public class BaseRelation {
    @Id
    @GeneratedValue
    private Long id;
...
// 維護(hù)一個(gè)Lover的人(節(jié)點(diǎn))與人(節(jié)點(diǎn))之間關(guān)系
// (p1:Person) -[r:Lover]-> (p2:Person)
@RelationshipEntity(type = "Lover")
public class Lover extends BaseRelation {
    @StartNode // 關(guān)系開始的節(jié)點(diǎn)
    private Person startNode;
    @EndNode // 關(guān)系目標(biāo)的節(jié)點(diǎn)
    private Person endNode;
...

節(jié)點(diǎn)的存儲(chǔ)的spring-data 的Repository

public interface LoverRepository extends Neo4jRepository<Lover, Long> {

}

關(guān)系的存儲(chǔ)的spring-data的Repository

public interface PersonRepository extends Neo4jRepository<Person, Long> {

}

測(cè)試一波

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Neo4jDemoApplication.class)
public class AppTest {
    @Autowired
    private PersonRepository personRepository;
    @Test
    public void testAddNode() {
        Person save = personRepository.save(new Person(1, "小明", "155***"));
        System.out.println(save);
    }
    @Test
    public void testAddNodes() {
        Iterable<Person> saveAll = personRepository.saveAll(Arrays.asList(new Person(2, "小偉", "133***"), new Person(3, "小紅", "188***"),
                new Person(4, "小芳", "186***")));
        saveAll.forEach(System.out::println);
    }

testAddNode 結(jié)果

image.png

image.png

testAddNodes結(jié)果

image.png

image.png

來來來,是時(shí)候給他們添加一波復(fù)雜的關(guān)系了

// 先需要把節(jié)點(diǎn)查出來(該方式中規(guī)中矩猜嘱,不太方便衅枫,后邊改進(jìn))
public interface PersonRepository extends Neo4jRepository<Person, Long> {
        // 自定義按userName查詢Person節(jié)點(diǎn)的方法  注意方法名稱 findBy**** 必須跟節(jié)點(diǎn)屬性名稱保持一致
    public Person findByUserName(String userName);
}
//測(cè)試代碼
    @Autowired
    private LoverRepository loverRepository;
    @Autowired
    private PersonRepository personRepository;
    @Test
    public void addLoverRelations() {
        // 為了不重復(fù)創(chuàng)建小紅、小明.... 需要先查詢
        Person xm = personRepository.findByUserName("小明");
        Person xw = personRepository.findByUserName("小偉");
        Person xh = personRepository.findByUserName("小紅");
        Person xf = personRepository.findByUserName("小芳");
        Lover xmLoverxw = new Lover(xm, xw);
        Lover xwLoverxh = new Lover(xw, xh);
        Lover xhLoverxm = new Lover(xh, xm);
        Lover xfLoverxh = new Lover(xf, xh);
        Iterable<Lover> saveAll = loverRepository.saveAll(Arrays.asList(xmLoverxw,xwLoverxh,xhLoverxm,xfLoverxh));
        saveAll.forEach(System.out::println);
    }

結(jié)果

image.png

image.png

會(huì)存在一個(gè)問題朗伶?

如何在保存節(jié)點(diǎn)或者關(guān)系的時(shí)候弦撩,做到不重復(fù)(按某個(gè)屬性區(qū)分)創(chuàng)建節(jié)點(diǎn)跟關(guān)系呢?

請(qǐng)聽下回分解...

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末论皆,一起剝皮案震驚了整個(gè)濱河市益楼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌点晴,老刑警劉巖感凤,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異粒督,居然都是意外死亡陪竿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哲银,“玉大人,你說我怎么就攤上這事入热∮拱” “怎么了解总?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)姐仅。 經(jīng)常有香客問我花枫,道長(zhǎng),這世上最難降的妖魔是什么掏膏? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任劳翰,我火速辦了婚禮,結(jié)果婚禮上馒疹,老公的妹妹穿的比我還像新娘佳簸。我一直安慰自己,他們只是感情好颖变,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布生均。 她就那樣靜靜地躺著,像睡著了一般腥刹。 火紅的嫁衣襯著肌膚如雪马胧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天衔峰,我揣著相機(jī)與錄音佩脊,去河邊找鬼。 笑死垫卤,一個(gè)胖子當(dāng)著我的面吹牛威彰,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播穴肘,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼歇盼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了梢褐?” 一聲冷哼從身側(cè)響起旺遮,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤赵讯,失蹤者是張志新(化名)和其女友劉穎盈咳,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體边翼,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡鱼响,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了组底。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片丈积。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡筐骇,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出江滨,到底是詐尸還是另有隱情铛纬,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布唬滑,位于F島的核電站告唆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏晶密。R本人自食惡果不足惜擒悬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望稻艰。 院中可真熱鬧懂牧,春花似錦、人聲如沸尊勿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽元扔。三九已至拼弃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間摇展,已是汗流浹背吻氧。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留咏连,地道東北人盯孙。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像祟滴,于是被迫代替她去往敵國(guó)和親振惰。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容